void effect_array(int ***ptr, int rows, int cols, int depth)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
for(int k = 0; k < depth; k++)
{
ptr[i][j][k] *= 2;
}
}
}
}
在我的尝试中,我成功地为2D/双重指针做了以下操作:
#include <stdio.h>
#include <stdlib.h>
void effect_array2d(int **ptr, int rows, int cols)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
ptr[i][j] *= 2;
}
}
}
int main()
{
int arr[2][2] = {
{1,2},
{3,4}
};
int **ptr = (int **)malloc(2 * sizeof(int *));
for(int i = 0; i < 2; i++) ptr[i] = arr[i];
printf("Array before pass to effect_array2d:\n");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
printf("\n");
effect_array2d(ptr, 2, 2);
printf("Array after pass to effect_array2d:\n");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
printf("\n");
free(ptr);
return 0;
}
给出的输出:
Array before pass to effect_array2d:
1 2
3 4
Array after pass to effect_array2d:
2 4
6 8
当我尝试将相同的方法用于3D数组和三重指针时,但是
#include <stdio.h>
#include <stdlib.h>
void effect_array(int ***ptr, int rows, int cols, int depth)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
for(int k = 0; k < depth; k++)
{
ptr[i][j][k] *= 2;
}
}
}
}
int main()
{
int arr[2][2][2] = {
{
{1,2},
{3,4}
},
{
{5,6},
{7,8}
}
};
int ***ptr = (int ***)malloc(2 * sizeof(int **));
for(int i = 0; i < 2; i++)
{
ptr[i] = arr[i];
}
free(ptr);
return 0;
}
我遇到了一个警告,说:
malloc3.c: In function ‘main’:
malloc3.c:34:16: warning: assignment to ‘int **’ from incompatible pointer type ‘int (*)[2]’ [-Wincompatible-pointer-types]
34 | ptr[i] = arr[i];
| ^
确定如何解决这个问题,或者我做错了什么。所有的帮助都将受到极大的赞赏。
我以前曾经看过这个问题,这是一个很艰难的问题,因为C处理3D阵列的差异与2D阵列有所不同。这是我为解决问题所做的工作:
#include <stdio.h>
#include <stdlib.h>
void effect_array(int ***ptr, int rows, int cols, int depth)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
for(int k = 0; k < depth; k++)
{
ptr[i][j][k] *= 2;
}
}
}
}
int main()
{
int arr[2][2][2] = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};
// Allocate memory for rows
int ***ptr = (int ***)malloc(2 * sizeof(int **));
// Allocate memory for columns in each row
for(int i = 0; i < 2; i++)
{
ptr[i] = (int **)malloc(2 * sizeof(int *));
for(int j = 0; j < 2; j++)
{
// Point to the correct part of the original array
ptr[i][j] = &arr[i][j][0];
}
}
printf("Array before:\n");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
for(int k = 0; k < 2; k++)
{
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
effect_array(ptr, 2, 2, 2);
printf("Array after:\n");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
for(int k = 0; k < 2; k++)
{
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
for(int i = 0; i < 2; i++)
{
free(ptr[i]);
}
free(ptr);
return 0;
}