创建具有随机值的链表

Creating a linked list with random values

我在解决以下任务时遇到问题:

"Write a C function RandList(n) that, given as input a positive integer n: creates a (unidirectional) linked list L of n elements; each element of the list contains a random integer value between -50 and 150 • RandList() returns 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);
}

虽然执行后我运行进入了segmentation fault错误。这个问题似乎与 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;
     }

在函数体中(添加正确的括号),主要的 运行s 的执行很好。不过,我不明白为什么会出现分段错误

      struct el* head;
      head -> data = -150;

head 没有指向任何有效的地方。更改它指向的任何内容 (???) 都是非法的。

这个声明

struct el* head;

声明了一个具有不确定值的未初始​​化指针。所以下面的语句

head -> data = -150;

调用未定义的行为。

在此语句中使用幻数 -150 也没有任何意义。

函数可以这样定义

struct el * RandList( size_t n )
{
    enum { MIN_VALUE = -50, MAX_VALUE = 150 };

    struct el *head = NULL;

    srand( ( unsigned int )time( NULL ) );

    for ( struct el *current, *new_el; 
          n-- && ( new_el = malloc( sizeof( struct el ) ) )!= NULL; )
    {
        new_el->data = rand() % ( MAX_VALUE - MIN_VALUE + 1 ) - MIN_VALUE;
        new_el->next = NULL;

        if ( head == NULL )
        {
            head = new_el;
            current = head;
        }
        else
        {
            current->next = new_el;
            current = current->next;
        }
    }

    return head;
}