Search code examples
carrayspointersmalloccalloc

C: Address of (c)allocated array does not fit with size of data type (I think....)


The following code is supposed to allocate some memory for a 2D array. I print their values and addresses to the screen but am confused about the output...

This is the C-code:

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

void print_2Darr( double **arr_2D, int N_rows, int N_cols );

int main(){

    int ii;

    const int N_cols = 4;
    const int N_rows = 3;

    double
        **arr;

    // note: for readibility, checking for NULL is omitted
    // allocate pointer to rows, then rows...
    arr    = calloc( (size_t)N_rows, sizeof *arr );
    arr[0] = calloc( (size_t)(N_rows*N_cols), sizeof **arr );
    // ... and set pointers to them
    for ( ii=1 ; ii<N_rows ; ++ii ) 
        arr[ii] = arr[ii-1] + N_cols;

    // print values their address of them
    print_2Darr( arr, N_rows, N_cols );

    // not to be forgotten...
    free( arr[0] );
    free( arr );

    return EXIT_SUCCESS;
}

void print_2Darr( double **arr_2D, int N_rows, int N_cols ) {
    int
        ii, jj;

    for ( ii=0 ; ii<N_rows ; ++ii) {
        for ( jj=0 ; jj<N_cols; ++jj)
            printf( "%f (%p)\t", arr_2D[ii][jj], (void*)&arr_2D[ii][jj] );
        printf( "\n" );
    }
}

Now comes the crucial part, the output might look like this:

0.000000 (0x12dc030)    0.000000 (0x12dc038)    0.000000 (0x12dc040)    0.000000 (0x12dc048)
0.000000 (0x12dc050)    0.000000 (0x12dc058)    0.000000 (0x12dc060)    0.000000 (0x12dc068)
0.000000 (0x12dc070)    0.000000 (0x12dc078)    0.000000 (0x12dc080)    0.000000 (0x12dc088)

I would have expected that the address would be higher by 8 byte walking through the array. Apparently, this is only true for every second step (from the 0th element to the 1st, then from the 2nd to the 3rd etc.). The address is advances by 8 byte, then 2 byte, then 8 byte, then 2 byte and so on.

What am I doing wrong, is it how I print the address?


Solution

  • The addresses ARE incrementing by 8 bytes. They are in hex.

    0x12dc030
    0x12dc038 - difference of 8 from the above
    0x12dc040 - difference of 8 from the above