arrayscpointers

Re-Organize 1d buffer as a 2d array


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?


Solution

  • Let's examine your code to understand why it does not work.

    Let's use a shorter buffer to understand what you are doing.

    Let's say you have:

    int buffer[9];
    

    and you want to treat it like a 3x3 2D array. Memory used buffer:

    buffer
    |
    v
    +---+---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+
    

    You want to create an int** p such that:

    p[0]        p[1]        [p2]
    |           |           |
    v           v           v
    +---+---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+
    

    In order to accomplish that, you have allocate memory to store p[0], p[1], and p[2]. That means, you need:

    int** p = new int*[3];
    p[0] = buffer;
    p[1] = buffer + 3;
    p[2] = buffer + 6;
    

    Now, p as well as p[0], p[1], p[2] point to valid addresses. You can use the syntax p[m][n].

    In our code, you just assigned p to point to the same location as buffer and by using the statement

    buf[i]=*(temp+i*c);
    

    you are just using the memory held by buffer as holders of int*, which not only tramples the data in buffer but also makes the values of the pointers unpredictable.

    Here's a working program.

    #include <stdio.h>
    
    int main()
    {
       int buffer[100];
       int rows = 4;
       int cols = 10;
       int **p = new int*[rows];
       for ( int i = 0; i < rows; ++i )
       {
          p[i] = buffer + i*cols;
          printf("%p\n", p[i]);
          for ( int j = 0; j < cols; ++j )
          {
             p[i][j] = i*2 + j*3;
          }
       }
       printf("\n");
    
       for ( int i = 0; i < rows; ++i )
       {
          for ( int j = 0; j < cols; ++j )
          {
             printf("%d ", p[i][j]);
          }
          printf("\n");
       }
    }