【问题标题】:Creating a linked list with random values创建具有随机值的链表
【发布时间】: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 -&gt; data,但您没有初始化head,因此分配的目的地未定义。

标签: c linked-list initialization singly-linked-list function-definition


【解决方案1】:
      struct el* head;
      head -> data = -150;

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

【讨论】:

  • 谢谢。添加此更改似乎可以解决问题:
  • struct el one; one.data = -150; one.next = NULL; struct el* head = &amp;one;
  • @PwNzDust...你会在哪里定义one?如果在函数内部,它会在函数返回时不复存在,并且指针 (head) 将变为无效。
  • 您需要为head 分配内存...类似于head = malloc(sizeof *head);
【解决方案2】:

此声明

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2017-01-28
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多