假设我有2个结构。
typedef struct name{
char*name;
struct test *next;
}name_t;
typedef struct test {
int grade;
int studentNumber;
struct test *next;
}test_t;
所以标记有一个指向测试的指针我将如何创建链接列表?
我试过这个
name_t *marker1 = malloc(sizeof(name_t));
// added name from another function
test_t *temp= malloc(sizeof(test_t));
// add the grade and student number from another function
if(marker1->next==NULL)
marker1->next=temp;
但它给了我错误
我该如何解决这个问题?这是我第一次编写链接列表,所以任何帮助将不胜感激
编辑:我也将以下内容变成了一个函数
void test(name_t* marker1,int data)
{
test_t *temp= malloc(sizeof(test_t));
test_t *location=NULL;
temp->grade=data;
temp->next=NULL;
location=marker1->next;
if(location==NULL)
{
// printf("%i \n",temp->grade);
marker1->next=temp;
}
else
{
while(location!=NULL)
{
printf("%i \n",location->grade);
printf("%p \n",location->next);
location=location->next;
}
location=temp;
}
}
由于某种原因,它似乎没有通过列表。为什么呢?
答案 0 :(得分:2)
struct test *next;
引用tag
名称test
。
typedef struct THIS_IS_WHERE_TAG_NAME_SHOULD_BE {
...
} test;
你在任何地方都没有这样的标签名称。添加它。
答案 1 :(得分:0)
程序的第二个块中有错误。你写过
if(marker1==NULL)
marker1->next=temp;
在此之前你已经写过了
name *marker1 = malloc(sizeof(name));
仅当malloc无法为您分配任何内存并返回NULL时,marker1才为NULL。当marker1为NULL时,您无法访问marker1-> next,这会导致分段错误。当您要求超过限制的内存量并且您编写的if语句不为真时,Malloc将返回NULL。但是应该避免if块中的语句。在指针为NULL时尝试访问数据的位置进行编码是错误的做法。