如何从1d中转出2darrays?
要访问我使用的任何元素*(Ptr + i)
。
有没有办法将2D数组放入分配的内存,以便使用array[i][j]
访问任何元素?
这是代码:
#include #include int main() { int *Ptr; Ptr = malloc(M*N*sizeof(int)); for (i = 0; i <= M * N; i++) *(Ptr + i) = 1 + rand()%10; return 0; }
样品
#include #include #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; }
试试这个:
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);