Home > software > C/C++ Pointer-Arithmetics

C/C++ Pointer-Arithmetics

February 17th, 2009 Leave a comment Go to comments

I recently found this when looking up how C/C++ organizes memory when allocating arrays, specifically multi-dimensional arrays.

You can access the array

#define X 5
#define Y 10
int data[X][Y];

either using

data[x][y]

or

*(*(data + x) + y)

Categories: software Tags: , ,
  1. stefan
    February 17th, 2009 at 16:37 | #1

    won’t this raise a compiler warning? I think I remember something about this…

  2. stefan
    February 17th, 2009 at 16:43 | #2

    @stefan
    warning just if it’s an array of char (string) in C…so just forget ;)

  3. February 17th, 2009 at 21:31 | #3

    :)

  4. robert
    February 18th, 2009 at 08:22 | #4

    Unfortunately this isn’t correct hundred percently.

    If you program C and define an N-dimensional !static! array, an one dimensional array will be used instead.

    What I’d say is that if you want to use an N-dimensional access to an array of values, you have to allocate the data in this way:


    // a will be 2-dimensional 20x10
    double** a=(double**)malloc(20*sizeof(double*));
    for (i=0;i<20;i++)
    a[i]=(double*)malloc(10*sizeof(double));

    Then you can access a in the 2-dim way a[i][j] instead of computing the index of your own a[i*10+j]. This on the other hand won’t work any more.

    If you’d define the array statically without a malloc, you can use both
    a[i][j] as well as a[i*10+j], since it’s an one dimensional field internaly

  5. February 18th, 2009 at 10:27 | #5

    @robert
    right he is, i think

  6. robert
    February 18th, 2009 at 10:44 | #6

    @Willi
    him or me?

  7. February 18th, 2009 at 10:45 | #7

    robert :

    @Willi
    him or me?

    Right YOU are – robert alias “java the hood”

  8. February 18th, 2009 at 12:54 | #8

    I think both infos are disjunct. Robert’s view is just a third way to do it.

  1. No trackbacks yet.