当我运行测试时,它会在循环中(无限期地)填充二维数组。
void assign(int** mat, int N, int M)
{
int *p;
for (p = &mat[0][0] ; p <= &mat[N-1][M-1] ; p++)
{
printf("Give an integer number : ");
scanf("%d", &*p) ;
}
}
主要程序:
int main(){//1- Dynamically allocate memory for array 2-D using double pointer
const int N=4; //#define N 4
const int M=4; //#define M 3
int **p = (int**) malloc(sizeof(int*) * N);
if (p == NULL)
{
printf("No allocated memory\n");
return EXIT_FAILURE;
}
for (unsigned i = 0; i < N; ++i)
{
p[i] = (int*)malloc(sizeof(int) * M);
if (p[i] == NULL)
{
printf("No allocated memory\n");
return EXIT_FAILURE;
}
}
assign(p, N, M);
Display(p, N, M);
return 0;}
我不确定为什么你在 for 循环上使用指针,但我假设你试图为二维数组中的每个元素获取输入,所以这样做。请注意 我正在使用一个指针来存储每个元素的地址,并存储 每个内存位置的值。希望这有帮助!
void assign(int **mat, int n, int m) {
int i, j;
int *p
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
p = &mat[i][j];
printf("Give an integer: ");
scanf("%d", p);
}
}
}
我添加主程序
int main(){//1- Dynamically allocate memory for array 2-D using double pointer
const int N=4; //#define N 4
const int M=4; //#define M 3
int **p = (int**) malloc(sizeof(int*) * N);
if (p == NULL)
{
printf("No allocated memory\n");
return EXIT_FAILURE;
}
for (unsigned i = 0; i < N; ++i)
{
p[i] = (int*)malloc(sizeof(int) * M);
if (p[i] == NULL)
{
printf("No allocated memory\n");
return EXIT_FAILURE;
}
}
assign(p, N, M);
Display(p, N, M);
return 0;}