【发布时间】:2020-10-30 23:42:30
【问题描述】:
我已经编写了一些代码,创建了一个单链表,然后将其转换为 C 中的动态数组。
如果我只为列表标题创建一个全局变量,代码就可以正常工作。但是,如果我想在我的 main 函数中创建列表,我总是会遇到分段错误。
只要我创建了一个全局列表变量并将列表作为参数从所有函数中删除,下面的代码就可以正常工作。
如果我想将列表作为参数传递给函数并因此能够创建多个列表,谁能告诉我为什么这不起作用?
#include <stdlib.h>
#include <stdio.h>
typedef struct NodeStruct* Node;
typedef struct NodeStruct {
Node next;
int val;
} NodeStruct;
typedef Node List;
Node newNode(int x){
Node n = (Node)malloc(sizeof(NodeStruct));
if(n!=NULL){
n->val = x;
n->next = NULL;
return n;
}
else{
printf("ERROR: Could not allocate memory!\n");
}
exit(1);
}
void prepend(List l, Node node){
if (l == NULL) l = node;
else{
node->next = l;
l = node;
}
}
void printList(List l){
if(l!=NULL){
Node n = l;
while(n->next != NULL){
printf("%d, ", n->val);
n = n->next;
}
printf("%d\n", n->val);
}
else{
printf("ERROR: List empty!\n");
}
}
/*=============================*/
int* arrOf(List l){
if(l==NULL){
printf("ERROR: List empty\n");
exit(1);
}
int size = 0;
Node n = l;
while(n!=NULL){
size++;
n = n->next;
}
int* arr = (int*)malloc((size+1)*sizeof(int));
n = l;
int i = 0;
arr[i++] = size;
while(n != NULL){
arr[i++] = n->val;
n = n->next;
}
printf("Returning Array\n");
return arr;
}
int main(int argc, char *argv[]){
List l;
prepend(l, newNode(5));
prepend(l, newNode(6));
prepend(l, newNode(7));
prepend(l, newNode(8));
prepend(l, newNode(9));
prepend(l, newNode(4));
printList(l);
printf("\n===========================================\n");
int* arr = arrOf(l);
for(int i = 0; i < 10; ++i){
printf("%d, ", arr[i]);
}
return 0;
}
【问题讨论】:
标签: c struct linked-list initialization singly-linked-list