对于学校项目,我们必须制作一个需要使用内存分配的程序。
我使用int *** array
,但是当我声明要使用它的内存时,我无法让它正常运行。我想这是因为在某些时候我调用了尚未分配的内存,尽管我找不到它。
该数组始终为3*size*unknown size
,其中未知在程序运行时动态分配。
arr = (int***)realloc(arr, sizeof(int**) * 3);
for (int n = 0; n < 3; n++) {
arr[n] = (int**)realloc(arr[n], sizeof(int*) * size);
}
for (int n = 1; n < 3; n++) {
for (int x = 0; x < size; x++) {
arr[n][x] = (int*)realloc(arr[n][x], sizeof(int));
arr[n][x][0] = n - 1;
}
}
感谢您的帮助。
答案 0 :(得分:1)
首先需要malloc
,然后realloc
,以防您想要更改内存的大小。
数组总是3 *大小*未知大小
首先,您首先使用malloc
int main (void)
{
int val = 1;
int LENGTH = 4;
const int SIZE = 10;
int ** arr[3];
for(int i=0; i < 3; i++)
{
arr[i] = (int**)malloc(sizeof(int*)*SIZE);
for (int j=0; j < SIZE; j++)
{
arr[i][j] = (int*)malloc(sizeof(int)*LENGTH);
for (int k=0; k < LENGTH; k++)
{
arr[i][j][k] = val++;
}
}
}
然后,当您想使用realloc
val = 1;
LENGTH = 8;
for(int i=0; i < 3; i++)
{
for (int j=0; j < SIZE; j++)
{
arr[i][j] = (int*)malloc(arr[i][j], sizeof(int)*LENGTH);
for (int k=0; k < LENGTH; k++)
{
arr[i][j][k] = val++;
}
}
}
然后你可以通过打印数组中的值来测试它
for(int i=0; i < 3; i++)
{
printf("---------- %d ----------\n", i);
for (int j=0; j < SIZE; j++)
{
for (int k=0; k < LENGTH; k++)
{
printf(" %d", arr[i][j][k]);
}
printf("\n");
}
printf("---------- %d ----------\n\n",i);
}
然后,当您完成数组后,可以使用free
for(int i=0; i < 3; i++)
{
for (int j=0; j < SIZE; j++)
{
free(arr[i][j]);
}
free(arr[i]);
}
return 0;
}
答案 1 :(得分:1)
如果只有最后一个维度未知,那么你可以编写更简单的代码:
#define lengthof(array) ( sizeof(array) / sizeof ((array)[0]) )
int *arr[3][size];
然后将它们全部设置为已知状态:
for (size_t i = 0; i != lengthof(arr); ++i)
for (size_t j = 0; j != lengthof(arr[i]); ++j)
arr[i][j] = 0;
然后改变大小:
for (size_t i = 0; i != lengthof(arr); ++i)
for (size_t j = 0; j != lengthof(arr[i]); ++j)
{
void *temp = realloc(arr[i][j], unknown_size * sizeof *arr[i][j])) )
if ( !temp )
exit(EXIT_FAILURE); // or other error handling
arr[i][j] = temp;
}
NB。如果将此分配代码放入函数中,请小心。
答案 2 :(得分:-3)
因为你的代码对我来说似乎是C ++:
int main()
{
int a, b, c;
int*** arr = new int**[a];
for (int i = 0;i < a;i++)
{
arr[i] = new int*[b];
for (int j = 0;j < b;j++)
{
arr[i][j] = new int[c];
}
}
}