c - C structure and malloc function
问题描述
I am new to programming.The other day I was playing around with structures and pointers...I was getting errors.I tried to rectify them.It got rectified...But I cant justify why there was an error at the first place.Please help me...
struct node{
int data;
struct node*next;
};
int main(){
struct node *newnode=NULL;
struct node *start=NULL;
newnode=start=(struct node*)malloc(sizeof(struct node));
newnode->data=1;
//code snippet
newnode->next=NULL;
newnode=newnode->next;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=2;
start=start->next;//error probably as start->next is perceived as NULL Address
printf("%d",start->data);
return 0;
}
when replacing code snippet with this code
newnode->next=(struct node*)malloc(sizeof(struct node));
newnode=newnode->next;
newnode->data=2;
start=start->next;
printf("%d",start->data);
error dissapers..How does one justify this ?
解决方案
You are overwritting the address of newnode
here
newnode = newnode->next;
You probably want:
start = malloc(sizeof(struct node));
start->data = 1;
newnode = malloc(sizeof(struct node));
newnode->data = 2;
newnode->next = NULL;
start->next = newnode;
printf("%d", start->data);
推荐阅读
- git - GitAhead 不断询问用户名和密码
- nuxt.js - Nuxt SSR 设置导致 Tailwind 媒体查询崩溃
- python - 在python的文本文件中退格一个字符串
- reactjs - reactjs:提供到公共文件夹的文件在生产构建中解析为 404 错误,但在开发中使用 npm start
- html - 如何使用jQuery关闭该元素的点击之外的元素?
- python - 理解这个 kivy 程序的确切错误告诉我的问题
- linux - RAD SERVER 10.4.1 “E2597(SystemPath)\ld-linux.exe: 错误: 找不到 -lz” 部署到 Linux 64
- python - 我正在尝试在 Python 中运行这个程序,但我无法执行 def
- java - 从 unix 命令行运行 jar 文件
- cuda - Cuda GPUassert:遇到非法内存访问