1

要访问我使用的任何元素*(Ptr + i)

有没有办法将二维数组放入分配的内存中,以便使用 访问任何元素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;
}
4

2 回答 2

5

样本

#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;
}
于 2013-03-31T16:20:03.487 回答
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);
于 2013-03-31T16:07:16.417 回答