Jason
Jason

Reputation: 1307

Difference between an array and a pointer to an array once compiled?

void m() {
    char a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    char(*c)[3][3] = (char (*)[3][3])a;
    printf("%d\n", *c[0][0]);
}

For instance, in this function the variable a points to a location in memory with 9 integers in a row.

But what about c? Does c point to a location in memory which points to a location in memory that holds 9 integers in a row?

So, technically, is c a single layer pointer or a double layer pointer?

Shouldn't what I said above be true? How come when I execute the below function:

void m() {
    char a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    char(*c)[3][3] = (char (*)[3][3])a;
    printf("%d\n", *c[0][0]);
    printf("a...%p\nc...%p\n", a, c);
}

a and c both point to the same locations? Shouldn't c be a double layer pointer, and a be a pointer to a location in memory?

Upvotes: 1

Views: 154

Answers (2)

user207421
user207421

Reputation: 310883

the variable a points to a location in memory with 9 integers in a row.

No. The variable a is a location in memory with 9 integers in a row. a is just a name for that location.

Does c point to a location in memory which points to a location in memory that holds 9 integers in a row?

No. c is a location in memory which points to a location in memory that holds 9 integers in a row. c is a name for the location containing the pointer.

So, technically, is c a single layer pointer or a double layer pointer?

Single.

Upvotes: 2

SHR
SHR

Reputation: 8313

Take a look of these type definitions:

typedef char9[9];
typedef char3x3[3][3];

If we check the sizes:

cout<<sizeof(char9); 

result will be always 9, there is no alignments in char array.

cout<<sizeof(char3x3);

if it is equal to 9, it is safe to say the bytes ordered the same as the one dimension array. if it is larger than 9, I would say there is alignment between rows, so there are holes between the lines, and then you can't map a pointer of one type upon the other.

Upvotes: 0

Related Questions