我正在尝试创建一个单链列表,并使用第一个给定的n个整数对其进行初始化。但是,每当我运行它时,都会遇到分段错误。这是我的代码。
typedef struct floatList{float fval;struct floatList * fnext;}node_f;
node_f* FL_firstInts(int n){
node_f *res=(node_f*)malloc(sizeof(node_f));
res=res->fnext;
for(int i=1;i<=n;i++){
res->fval=i;
res=res->fnext;
}
return res;
}
void FL_show(struct floatList *list, char *label){
int i=0;
while(list->fnext!=NULL){
printf("%d: %f\n",i,f->fval);
list=list->fnext;
i++;
}
}
为了测试主函数,我写了以下内容
node_f *ten = FL_firstInts(10);
FL_show(ten,"10 first integers");
但是在我运行程序时,出现了分段错误,该如何解决?
在函数FL_firstInts
中分配了node_f类型的未初始化对象
node_f *res=(node_f*)malloc(sizeof(node_f));
所以下面的语句
res=res->fnext;
已经调用未定义的行为。
至少可以通过以下方式定义功能
node_f * FL_firstInts( int n )
{
node_f *head = NULL;
node_f **current = &head;
`
for ( int i = 0; i < n; i++ )
{
*current = malloc( sizeof( node_f ) );
( *current )->fval = i;
( *current )->fnext = NULL;
current = &( *current )->fnext;
}
return head;
}
此功能FL_show
具有相同的错误,并且未使用参数label
。
该函数可以这样定义
void FL_show( const node_f *head, const char *label )
{
for ( int i = 0; list != NULL; list = list->fnext )
{
printf( "%d: %f\n", i, f->fval );
i++;
}
}
node_f *res=(node_f*)malloc(sizeof(node_f));
res=res->fnext;
崩溃的原因是,您从未初始化res->fnext
指针。因此,在访问它之前,将其设置为列表中实际的下一个元素。
通常,您的代码有点模糊。您正在为one node_f
分配内存,但实际上是在尝试将n
元素放入其中。
要为n
元素分配内存,只需将一个元素的大小乘以n
。
node_f *res= (node_f*) malloc(sizeof(node_f) * n);
然后初始化fnext
指针。
for(size_t index{0}; index < n - 1; index++)
res[index].fnext = &res[index + 1];
res[n - 1].fnext = nullptr;