C 使用指针到指针时出现分段错误
我一直试图在函数中使用指向指针的指针,但似乎我没有正确地进行内存分配。。。 我的代码是:C 使用指针到指针时出现分段错误,c,function,pointers,C,Function,Pointers,我一直试图在函数中使用指向指针的指针,但似乎我没有正确地进行内存分配。。。 我的代码是: #include<stdio.h> #include<math.h> #include<ctype.h> #include<stdlib.h> #include<string.h> struct list{ int data; struct list *next; }; void abc (struct list
#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
struct list{
int data;
struct list *next;
};
void abc (struct list **l,struct list **l2)
{
*l2=NULL;
l2=(struct list**)malloc( sizeof(struct list*));
(*l)->data=12;
printf("%d",(*l)->data);
(*l2)->next=*l2;
}
int main()
{
struct list *l,*l2;
abc(&l,&l2);
system("pause");
return(0);
}
#包括
#包括
#包括
#包括
#包括
结构列表{
int数据;
结构列表*下一步;
};
无效abc(结构列表**l,结构列表**l2)
{
*l2=零;
l2=(结构列表**)malloc(sizeof(结构列表*);
(*l)->数据=12;
printf(“%d”,(*l)->数据);
(*l2)->next=*l2;
}
int main()
{
结构列表*l,*l2;
作业成本法(&l和&l2);
系统(“暂停”);
返回(0);
}
这段代码可以编译,但我无法运行程序。我遇到了一个分段错误。我该怎么办?如果有任何帮助,将不胜感激 此部分不正确:
l2=(struct list**)malloc( sizeof(struct list*));
(*l)->data=12;
您不能分配给未分配的结构。正确的代码大致如下:
*l = malloc(sizeof(struct list));
(*l)->data = 12;
碰撞是由于
(*l)->数据=12因为(*l)
实际上是一个统一变量。请注意,l
和l2
在main中声明为指针,并且没有一个初始化为指向任何东西。因此您有两种选择,要么在main
中初始化指针,然后在abc
中使用它们,要么在abc
中初始化指针
根据您编写的内容,您似乎希望在abc
中进行初始化。为此,您必须malloc
足够的内存来容纳struct list
,然后将指针设置为指向该内存。生成的abc
函数如下所示
void abc( struct list **l, struct list **l2 )
{
*l = malloc( sizeof(struct list) );
*l2 = malloc( sizeof(struct list) );
if ( l == NULL || l2 == NULL )
{
fprintf( stderr, "out of memory\n" );
exit( 1 );
}
(*l)->data = 12;
(*l)->next = *l2;
(*l2)->data = 34;
(*l2)->next = NULL;
printf( "%d %d\n", (*l)->data, (*l2)->data );
}
不要对malloc的结果进行强制转换:强制转换既错误又不必要。您正在取消对未初始化数据的引用。简而言之,这大部分都是错误的。您将l2
作为参数接收,但您忽略了它,并将其设置为指向通过malloc()
获得的新结构。如果我们不必猜测您正在尝试做什么,这将非常有用。调用abc(&l,&l2)
后,返回main()
中的l
和l2
的预期结果是什么?为了获得更好的答案,即使您正在尝试学习,也应该为abc
函数定义用途,例如创建链接列表(也许您甚至应该更改函数的名称)。