C语言链表的问题,请教一下。

怎么给链表里的数复值,看看我这个程序哪儿错了?
#include "stdio.h"
struct link
{
int n;
link *next;
};
link *head;
int main()
{
head->n=100;
printf("%d\n",head);
return 0;
}
编译没有错误,但是运行的时候显示内存不能为"written"。
请大家解释一下,谢谢了。
那个早试过了,如果按照一楼说的这么改的话。会出现内存不能为"read"。

你用link前应该给link分配内存......

用malloc就好了
还有printf要按照上面的改
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-11-14

struct link
{
int n;
link *next;
};
改为
struct link
{
int n;
struct link *next;
};

link *head; 改为struct link *head;

printf("%d\n",head);
改为printf("%d\n",head->n);
第2个回答  2008-11-14
你没有给head所指对象分配内存啊。
在main里第一行插入
head=(struct link*)malloc(sizeof(struct link));
这样就可以了,但是输出是printf("%d\n", head->n);否则打印的是内存地址。
第3个回答  2008-11-15
#include"stdio.h"
struct link
{
int n;
struct link *next;
};
struct link *head={100};
int main()
{
printf("%d\n",head);
return 0;
}

这样就可以了
注意赋值方式

那应该是其他问题,程序我在tc里成功运行。
不信可以在其他机器上运行一下的。
看一下

内存不能为"read"及"written"的问题答案吧。
相似回答