尝试研究链表并在终端和Xcode上的gcc 4.1.2上尝试了我的程序。
xcode 错误:线程 1:Exe_BAD_ACCESS(代码 = 1)终端错误;分段错误
而且我不知道Xcode错误是什么。 出于某种原因,对于在其他 GCC 上运行的某些程序,它给了我同样的错误?
法典:
#include <stdio.h>
#include <stdlib.h>
typedef struct node *link;
struct node {int item; link next;};
int main(int argc, const char * argv[]) {
int i;
link t = malloc(sizeof *t);
while ( t != NULL)
{
for ( i = 0; i < 10;i++)
{
t->item = i;
t = t->next;
}
}
int count = 0;
while ( t != NULL)
{
for ( i = 0; i < 10; i++)
{
if (count == 3)
{
printf("%dn", t->item);
continue;
}
t = t->next;
count++;
}
}
}
您取消了引用t->next
,这是通过malloc()
分配的,没有分配一些值,并调用了未定义的行为。您必须为第二个节点及以后的节点分配缓冲区。
此外,在处理列表之前,您应该将指针t
取回。
#include <stdio.h>
#include <stdlib.h>
typedef struct node *link;
struct node {int item; link next;};
int main(int argc, const char * argv[]) {
int i;
link t = malloc(sizeof *t);
link head = t; /* add this line to get the pointer back */
while ( t != NULL)
{
for ( i = 0; i < 10;i++)
{
t->item = i;
t->next = malloc(sizeof *t); /* add this line */
t = t->next;
}
}
int count = 0;
t = head; /* add this line to get the pointer back */
while ( t != NULL) /* convinated with inner loop, this will lead to infinite loop */
{
for ( i = 0; i < 10; i++) /* you may want to check if t != NULL here for safety */
{
/* not invalid but odd program that print the 4th element again and again */
if (count == 3)
{
printf("%dn", t->item);
continue;
}
t = t->next;
count++;
}
}
}