【问题标题】:How use a dynamic array with a structure如何使用具有结构的动态数组
【发布时间】:2021-01-26 21:25:26
【问题描述】:

我已经编写了一个堆排序程序,我试图将数组和数组的大小放在一个结构中,但我的代码中似乎有一些错误(我认为它在初始化部分)。 这是我的代码。

#include<stdio.h>
#include<stdlib.h>

int cmp;

typedef struct heap
{
    int *arr, n;
}heap;

void main()
{
    heap *h;
    scanf("%d",&h->n);
    h->arr = (int*)malloc(h->n*sizeof(int));
    
    for(int i=0; i<h->n; i++)
        scanf("%d",h->arr+i);
    
    build_heap(h);
    heap_sort(h);
    
    for(int i=0; i<h->n; i++)
        printf("%d ",h->arr[i]);
    printf("\n%d\n",cmp);
    free(h->arr);

}

我在linux平台编译,得到的错误是Segmentation fault (core dumped) Can someone explain why I got this error and give a possible solution to this.

【问题讨论】:

  • 在将h 声明为未初始化的heap * 后直接使用h-&gt;nh-&gt;arr 是不正确的。相反,将h 声明为heap 并使用h.nh.arr。请记住,h-&gt;n 只不过是(*h).n 的同义词,在未初始化的指针上使用* 运算符最多会导致分段错误。

标签: c sorting struct heapsort


【解决方案1】:

当您声明 heap *h; 时,您声明了一个指针,但在您从未将 h 初始化为指向任何地方之后。

你可能想要这个:

int main()
{
  heap h;                              // now h is a heap and no more a pointer to heap
  scanf("%d", &h.n);
  h.arr = malloc(h.n * sizeof(int));   // the cast to (int*) is useless

  for (int i = 0; i < h.n; i++)
    scanf("%d", h.arr + i);            //BTW: &h.arr[i] would be more readable

  build_heap(&h);
  heap_sort(&h);

  for (int i = 0; i < h.n; i++)
    printf("%d ", h.arr[i]);

  printf("\n%d\n", cmp);
  free(h.arr);
}

build_heapbuild_heap 可能还有更多问题,但我不能告诉你更多,因为你没有展示这些功能。

【讨论】:

    【解决方案2】:

    换一种方式:

    typedef struct heap
    {
        size_t n;
        int arr[]; 
    }heap;
    

    只需要一个mallocfree

        size_t size;
        heap *h;
    
        if(scanf("%zu", &size) != 1) { /* error handling*/};
        h = malloc(sizeof(*h) + size * sizeof(h -> arr[0]));
        if(!h) { /* error handling*/};
        h -> size = size;
    
        /*...... */
    
    
        free(h);
    

    【讨论】:

      【解决方案3】:

      通过这样做heap *h;,你已经声明了一个指向堆结构的指针,但是这个指针实际上指向的是什么?

      你只需要为你的堆分配内存:

      void main()
      {
          heap *h;
          // Alloc and initialize the pointer to the heap
          h = malloc(sizeof(heap));
          scanf("%d",&h->n);
          h->arr = malloc(h->n*sizeof(int));
          
          for(int i=0; i<h->n; i++)
              scanf("%d",h->arr+i);
          
          build_heap(h);
          heap_sort(h);
          
          for(int i=0; i<h->n; i++)
              printf("%d ",h->arr[i]);
          printf("\n%d\n",cmp);
          free(h->arr);
      
          // Don't forget to free the heap as well!
          free(h);
      
      }
      

      此外,最好不要强制转换 malloc 的返回值。

      【讨论】:

        猜你喜欢
        • 2019-07-19
        • 2021-12-16
        • 1970-01-01
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多