简体   繁体   中英

Memory allocation for 2D array in C

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM