首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用具有结构的动态数组

如何使用具有结构的动态数组
EN

Stack Overflow用户
提问于 2020-10-12 22:38:29
回答 3查看 39关注 0票数 0

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

代码语言:javascript
复制
#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.

EN

回答 3

Stack Overflow用户

发布于 2020-10-12 22:52:03

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

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

代码语言:javascript
复制
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的返回值。

票数 3
EN

Stack Overflow用户

发布于 2020-10-12 22:58:33

用一种不同的方式:

代码语言:javascript
复制
typedef struct heap
{
    size_t n;
    int arr[]; 
}heap;

只需要一个mallocfree

代码语言:javascript
复制
    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);
票数 1
EN

Stack Overflow用户

发布于 2020-10-12 23:05:21

当你声明heap *h;时,你声明了一个指针,但是在声明之后,你永远不会将h初始化为指向任何地方。

你可能想要这个:

代码语言:javascript
复制
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中可能会有更多的问题,但我不能告诉你更多,因为你没有展示这些函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64319984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档