Memory allocation for 2D array in C

让人想犯罪 __ 提交于 2019-12-13 04:13:34

问题


I am writing a multithreaded C program and I have an error. I have a 2D array array worker_table declared globally as:

int **worker_table;

And allocated in main as follows:

worker_table        = (int**) calloc(number_of_workers*2,(sizeof(int)));

This is the worker function:

    void *Worker(void *worker_id)
    {

my_id = (int)worker_id;    //id of the worker
printf("Line 231\n");
printf("My id is %d\n",my_id);
my_customer = worker_table[my_id][1];//line 233
printf("Line 234\n");
int my id;

The error happens before line 234, I think what is wrong is on line 233, but I can't figure out what it is.


回答1:


Your allocation is wrong. It should be like this:

worker_table = calloc(number_of_workers,(sizeof(int*)));
for(int i = 0; i < 2; ++i)
{
   worker_table[i] = calloc(2, sizeof(int));
}

And the freeing procedure should be:

for(int i = 0; i < 2; ++i)
{
    free(worker_table[i]);
}
free(worker_table);

I suggest that you should read a good book on C




回答2:


You have only allocated one dimension of your 2d array.

This is how you can allocate the second dimension:

worker_table = malloc(number_of_workers * (sizeof(int*)));
for(size_t i = 0; i < 2; ++i)
  worker_table[i] = calloc(2, sizeof(int));

Or access it using some multiplication:

int* worker_table = calloc(number_of_workers*2,(sizeof(int)));
my_customer = worker_table[x + y * number_of_workers];


来源:https://stackoverflow.com/questions/8778285/memory-allocation-for-2d-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!