yulian
yulian

Reputation: 1627

How to turn 2d array out of 1d one?

To access any element I use *(Ptr + i).

Is there any way to put 2D array into the allocated memory in order to access any element using array[i][j]?

Here is the code:

#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;
}

Upvotes: 1

Views: 184

Answers (2)

Wintermute
Wintermute

Reputation: 1531

Try this:

int** theArray;  
theArray = (int**) malloc(M*sizeof(int*));  

    for (int i = 0; i < M; i++)
    {
        theArray[i] = (int*) malloc(N*sizeof(int));
    }

Sample:

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);

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40145

Sample

#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;
}

Upvotes: 5

Related Questions