C中2D数组的内存分配 [英] Memory allocation for 2D array in C

查看:107
本文介绍了C中2D数组的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写多线程C程序,但出现错误。
我有一个二维数组 array worker_table 全局声明为:

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;

在main中的分配方式如下:

And allocated in main as follows:

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

这是辅助函数:

    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;

错误发生在第234行之前,我认为第233行出了问题,但是我可以

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));
}

释放程序应为:

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

我建议您阅读关于C的好书

这篇关于C中2D数组的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆