user3270649
user3270649

Reputation: 31

How c-array would be stored/represented in memory

char buffer[]="foobar";

I know that buffer is char* pointer to the first element so buffer==&buffer[0] but why &buffer==buffer? &buffer should give the memory address of the buffer char* and NOT the address of the first element?

Additionaly,What would happen when i do (int)buffer ?

Upvotes: 1

Views: 120

Answers (2)

Kraken
Kraken

Reputation: 24213

Think of it like this.

buffer is the address of the first element of the array. So it is the address of an integer.

&buffer is the address of the array. Hence &buffer will be in fact the same as buffer, but their behaviour will be different.

For e.g. if you do buffer+1, it will increment by the size of int, but &buffer+1 will increment by the size of the array, i.e size of one element * number of elements.


Edits. Initially I had written buffer++ instead of buffer+1. See comments section for the reason I edited it.

Upvotes: 0

Baptiste Wicht
Baptiste Wicht

Reputation: 7663

buffer is the address of the first element and &buffer is indeed the address of the array itself. The array will be stored on the stack directly. That is why &buffer == buffer.

It is not a pointer but an array. If you had declared it as char*, it would not be &buffer == buffer

Upvotes: 1

Related Questions