要访问我使用*(Ptr + i)
的任何元素。
有没有办法将2D数组放入已分配的内存中,以便使用array[i][j]
访问任何元素?
以下是代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *Ptr;
Ptr = malloc(M*N*sizeof(int));
for (i = 0; i <= M * N; i++)
*(Ptr + i) = 1 + rand()%10;
return 0;
}
答案 0 :(得分:4)
样品
#include <stdio.h>
#include <stdlib.h>
#define N 4
#define M 3
int main()
{
int *Ptr;
int (*p)[M];
int i,j;
Ptr = malloc(M*N*sizeof(int));
for (i = 0; i < M * N; i++){
*(Ptr + i) = 1 + rand()%10;
// printf("%d ", Ptr[i]);
}
// printf("\n");
p=(int (*)[M])Ptr;//p[N][M]
for(i = 0; i < N ;++i){
for(j = 0; j < M;++j)
printf("%d ", p[i][j]);
printf("\n");
}
return 0;
}
答案 1 :(得分:1)
试试这个:
int** theArray;
theArray = (int**) malloc(M*sizeof(int*));
for (int i = 0; i < M; i++)
{
theArray[i] = (int*) malloc(N*sizeof(int));
}
样品:
int M = 5;
int N = 5;
int** theArray = (int**) malloc(M*sizeof(int*));
for (int i = 0; i < M; i++)
{
theArray[i] = (int*) malloc(N*sizeof(int));
for(int j = 0 ; j < N; j++)
{
theArray[i][j] = i+j;
printf("%d ", theArray[i][j]);
}
printf("\n");
}
for (int k = 0; k < M; k++)
{
free(theArray[k]);
}
free(theArray);