首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用空指针将任何类型的数据存储在节点中(可以是int char或结构)

使用空指针将任何类型的数据存储在节点中(可以是int char或结构)
EN

Stack Overflow用户
提问于 2014-01-25 12:13:09
回答 1查看 744关注 0票数 0
代码语言:javascript
复制
#include<stdio.h>
#include<stdlib.h>

struct genericStorage
{
  void *data;
  int type;
};


struct genericNode
{
  struct genericStorage storage;
  struct genericNode *next;
};

struct genericNode *new,*temp;

struct genericNode* createGLL(int type)
{
  int a;
  char b;


  if(type==0)
    {
      new=(struct genericNode *) malloc (sizeof(struct genericNode));
      (new->storage).data=(int *) malloc (sizeof(int));
      printf("Enter Integer");
      scanf("%d",&a);
      *((int *)(new->storage.data))=a;
      new->storage.type=type;
      new->next=NULL;

    }
  else if(type==1)
    {
      new=(struct genericNode *) malloc (sizeof(struct genericNode));
      (new->storage).data=(char *) malloc (sizeof(char));
      printf("Enter Char");
      scanf("%c",&b);
      *((char *)(new->storage.data))='c';
      new->storage.type=type;
      new->next=NULL;

    }
    else if(type==2)
    {
      new=(struct genericNode *) malloc (sizeof(struct genericNode));
      temp=(struct genericNode *) malloc (sizeof(struct genericNode));
      temp=createGLL(1);
      (new->storage).data=(struct genericNode *)temp;
      new->storage.type=type;
      new->next=NULL;
    }
}

void print(struct genericNode *t)
{
  if(t->storage.type==0)
    printf("%d\n",*(int *)t->storage.data);
  if(t->storage.type==1)
    printf("%c\n",*(char *)t->storage.data);
  if(t->storage.type==2)
    printf("%c\n",*(struct genericNode *)(t->storage.data->(temp->storage).data));

}

int main()
{
  int type;

  struct genericNode *head;
  head=NULL;
  printf("Enter the type");
  scanf("%d",&type);
  getchar();
  head=createGLL(type);
  print(head);
  return 0;
}

在打印函数中,我遇到了一个问题,我必须打印存储在外部结构中的结构中的数据。如何访问内部结构中的数据并打印出来?请紧急提供帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-25 12:22:27

(t->storage.data->(temp->.data))

这句话说不通。您正在尝试访问storage.data中的一个成员,但是您可以访问temp中的一个成员,而不是一个有效成员的名称。根本不是C。

如果我理解您的代码,t->storage.data可能是指向genericNode的另一个指针。在这种情况下,您可能希望这样做:

代码语言:javascript
复制
if(t->storage.type == 2) {
    struct genericNode *node = t->storage.data;
    printf("Jumping to the inner genericNode at %p\n", (void *)node);

    print(node); /* Call print again. */
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21350353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档