混合动态和静态分配[重复]

时间:2021-02-11 17:00:33

This question already has an answer here:

这个问题在这里已有答案:

I have a 3D array as such char **arr[1];

我有一个3D数组,如char ** arr [1];

I have it dynamically allocated like that:

我有动态分配它:

*arr = calloc(10, sizeof(char*)); // Will be using 0-9
for(i = 0; i < 10; i ++)
    *arr[i] = malloc(3); // will be using 0-2

It crashes. Even though, I can't provide you with the entire library, in which I read/write to that array, but the answer of the question is the allocation correct, will help me debug and throw out the possibility of wrong or impossible allocation.

它崩溃了。即便如此,我无法为您提供整个库,我在其中读取/写入该数组,但问题的答案是分配正确,将帮助我调试并抛弃错误或不可能分配的可能性。

1 个解决方案

#1


0  

I would do it like this:

我会这样做:

char** arr;
arr = malloc(10 * sizeof *arr);
if (!arr)
  return -1;
for (int i = 0; i < 10; i++)
{
  arr[i] = malloc(3);
  if (!arr[i])
    return -1;
}

if you really need this 3d array, the correct way should be:

如果你真的需要这个3d数组,正确的方法应该是:

char** arr[1];
arr[0] = malloc(10 * sizeof **arr);
if (!arr[0])
  return -1;
for (int i = 0; i < 10; i++)
{
  arr[0][i] = malloc(3);
  if (!arr[0][i])
    return -1;
}

when you are done you should free the memory like this (this works for the second example):

当你完成后你应该释放这样的内存(这适用于第二个例子):

for (int i = 0; i < 10; i++)
  free(arr[0][i]);
free(arr[0]);

other methods are: char arr[3][10]; or char arr[1][3][10];, but an array with only 1 value doesn't make much sense.

其他方法是:char arr [3] [10];或char arr [1] [3] [10];,但只有1值的数组没有多大意义。

#1


0  

I would do it like this:

我会这样做:

char** arr;
arr = malloc(10 * sizeof *arr);
if (!arr)
  return -1;
for (int i = 0; i < 10; i++)
{
  arr[i] = malloc(3);
  if (!arr[i])
    return -1;
}

if you really need this 3d array, the correct way should be:

如果你真的需要这个3d数组,正确的方法应该是:

char** arr[1];
arr[0] = malloc(10 * sizeof **arr);
if (!arr[0])
  return -1;
for (int i = 0; i < 10; i++)
{
  arr[0][i] = malloc(3);
  if (!arr[0][i])
    return -1;
}

when you are done you should free the memory like this (this works for the second example):

当你完成后你应该释放这样的内存(这适用于第二个例子):

for (int i = 0; i < 10; i++)
  free(arr[0][i]);
free(arr[0]);

other methods are: char arr[3][10]; or char arr[1][3][10];, but an array with only 1 value doesn't make much sense.

其他方法是:char arr [3] [10];或char arr [1] [3] [10];,但只有1值的数组没有多大意义。