Question: I am given a 1d buffer (`int buffer[100]`) of sufficient size. I need to re-organize the same memory as a 2d array. What i am trying to do is typecast it into a double pointer(`int ** p`) and then pass the pointer to the alloc function which will do the reorganizing. After the function returns, i need the statement `p[2][2]` to work.

This is the code:

```
#include <stdlib.h>
#include <stdio.h>

void alloc(int ** buf, int r, int c)
{
    int **temp;
    temp=buf;
    for(int i=0;i<r;i++)
        buf[i]=*(temp+i*c);
}
void main()
{
    int buffer[100];
    int **p=(int **)buffer;
    alloc(p, 4, 4);
    p[2][2]=10;
    printf("%d", p[2][2]);
}

```

The above code compiles successfully, but when i run the code i get an access violation upon execution of the statement 

```
p[2][2]=10;

```

I'm failing to understand where the problem lies. Is there a problem with the alloc function? Or is the problem somehwere else?

Answer: 
```
#include <stdio.h>

int main(){
    int buffer[100];
    int (*p)[4]=(int (*)[4])buffer;//int p[25][4]

    p[2][2]=10;
    printf("%d\n", p[2][2]);
    printf("%d\n", buffer[4*2+2]);//10
    return 0;
}

```
You can not *convert* 1D array to 2D. In fact, every multi-dimensional array is just a 1D/linear collection of cells, programming language creates the illusion of multi-dimensionality. You can create the same illusion, i.e. make an abstraction of a 1D array, so that it *looks* like a 2D (any any higher dimension)

You can do this:

```
#define ROW 10
#define COL 10

int arr[size]={1,2...}; //I am making it global, you can declare it anywhere

int& getValueFrom2DArray(int row,int col) // return type is a reference, so that you can assign
{
 if( row>= ROW || col >= COL)
  return -1; //treating -1 as sentinel value
 return array[ row*COL + col]; // convert 2D co-ordinates into 1D position
}

int main() //return type of main should be int, not void
{
   getValueFrom2DArray(2,2) = 10;
   cout<< getValueFrom2DArray(2,2)<<endl;
   return 0;
}

```