【发布时间】:2021-12-07 13:03:43
【问题描述】:
我在解决以下任务时遇到问题:
"编写一个 C 函数 RandList(n),将其作为输入给定一个正数 整数 n:创建一个包含 n 个元素的(单向)链表 L; 列表的每个元素都包含一个介于 -50 之间的随机整数值 和 150 • RandList() 返回 L"
目前我写的代码是这样的:
struct el{
int data;
struct el* next;
};
struct el* RandList(int n){
srand( (unsigned) time(NULL));
int i;
struct el* head;
head -> data = -150;
struct el* p;
for (i=0;i<n;i++){
struct el* temp = malloc(sizeof(struct el));
temp -> data =(rand()%200-50);
temp -> next = NULL;
if (head->data == -150){
head = temp;
}
else{
p=head;
while (p->next != NULL){
p=p->next;
}
p->next = temp;
}
}
return head;
}
int main(){
struct el* head = RandList(4);
printf("%d\n", head -> data);
}
虽然在执行后我遇到了分段错误错误。这个问题似乎与p=head 有关,因为如果我简单地写:
struct el* RandList(int n){
srand( (unsigned) time(NULL));
int i;
struct el* head;
head -> data = -150;
struct el* p;
for (i=0;i<n;i++){
struct el* temp = malloc(sizeof(struct el));
temp -> data =(rand()%200-50);
temp -> next = NULL;
if (head->data == -150){
head = temp;
}
在函数体中(添加正确的括号),main 的执行运行良好。不过,我不明白为什么会出现分段错误
【问题讨论】:
-
无关:将
srand()移出RandList()并移入main() -
您将
-150分配给head -> data,但您没有初始化head,因此分配的目的地未定义。
标签: c linked-list initialization singly-linked-list function-definition