0

I have the following program in C. I use malloc to allocate space for a float array of 2048x2048. I have the pointer to this array and I want to index with array indexes like table[1][2].

I know I could use malloc like this:

float ** table;
table = (float **) malloc(2048*sizeof(float*));
for(i=0;i<2048;i++)
    table[i]=(float *) malloc(2048*sizeof(float));
//now table[1][2] works just perfect

But I prefer to malloc a solid piece of memory and that's why I used a struct that contains the required table.

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

struct ftable
{
    float table[2048][2048];
};

typedef struct ftable ftable;

int main(void)
{
    ftable * A_table;
    A_table = (ftable *)malloc(sizeof(ftable));
    if (!A_table)
    {
        puts("Error allocating memory...");
        exit(1);
    }

    float * A;
    A = (float *)A_table;

    float ** B;
    B = (float **)A_table;

    //I want to access A[1][2]
    //------------   1st way  -------------- works ok
    A[1 * 10 + 2] = 5.0;
    //or
    *(A + 12) = 5.0;

    //------------   2nd way  -------------- doesn't work
    B[1][2] = 5.0;

    //finish
    free(A_table);
    getchar();
    return 0;
}

I want to index the array this way: A[i][j] and not like A[i*columns + j] because later I'm going to use openmp to optimize some for loops and normal array indexing is required. I'm stuck here and I need your help.

marmotas
  • 29
  • 1
  • 8

2 Answers2

2

The struct way of doing it is fine, but you have to access the array member:

A = malloc(sizeof ftable);

A.table[3][4] = . . .
Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
  • but I use this code float * A = (float *)A_table; and I use directly the pointer to float – marmotas Mar 30 '15 at 23:22
  • But you can't do 2D indexing on a simple `float*`. The compiler needs to know the size of the first index. – Lee Daniel Crocker Mar 30 '15 at 23:26
  • yes you are right. Otherwise I will have to do it manually like A[3*2048 + 4] or *(A + 3*2048 + 4). I didn't want to use the struct - BLUEPIXY gave the answer I wanted. Thanks a lot! – marmotas Mar 30 '15 at 23:32
0

If you actually do not want to use the struct at all (as suggested in comments), you can write:

float (*table)[COLUMNS] = malloc( ROWS * sizeof *table );

and then use table[row][col] to access each cell.

See here if you are unfamiliar with the malloc(N * sizeof *p) pattern.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365