开发者

In C, how to initialize a pointer-to-pointers from inside a function?

Following this answer, I made a simple example to be sure I properly understood:

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

typedef struct
{
  int x;
} data;

void fill_data (data *** ptr_all, int l)
{
  int i = 0;
  *ptr_all = (data**) calloc(l, sizeof(data));
  if ((*ptr_all) == NULL){
    fprintf(stderr, "error: can't allocate memory");
    abort();
  }
  for (i = 0; i < l; i++)
  {
    data * d = (data*) calloc(1, sizeof(data));
    if (d == NULL){
      fprintf(stderr, "error: can't allocate memory for %i-th data", i+1);
      abort();
    }
    d->x = i;
    (*ptr_all)[i] = d;
  }
}

int main(int argc, char *arg开发者_JAVA百科v[])
{
  int i = 0, l = 5;
  data ** all = NULL;

  fill_data (&all, l);

  for (i = 0; i < l; i++)
  {
    printf("%i\n", all[i]->x);
  }

  return EXIT_SUCCESS;
}

However, after compiling and running it, I see that the first element is wrong:

$ gcc -Wall test.c
$ ~/bin/a.out 
161276080
1
2
3
4

I can see that in my function fill_data I don't initialize ptr_all, but only *ptr_all, and this may be the cause of the problem. But how should I do?


Change:

*ptr_all = (data**) calloc(l, sizeof(data));

to:

*ptr_all = (data**) calloc(l, sizeof(data*));

You're allocating l ints whereas you need to be allocating l pointers. You're almost certainly building and running this on a 64 bit OS (where sizeof(void *) > sizeof(int)), otherwise this bug would have remained dormant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜