Home > Enterprise >  Array name and pointer
Array name and pointer

Time:12-30

I was reading this answer- https://stackoverflow.com/a/1644292/10352155

After reading this,I have some doubts which goes as follows-

It is said in the answer that, as soon as that array expression "decays" to a pointer, all you have is a pointer to a single element.

So does it means that when the array expression is getting converted to a pointer, an extra memory space(other than the memory spaces already allocated for the array elements) of required bytes is allocated to store the value of the pointer expression(which is none other than the base address of the array)?

If this is so, then how is it different from the language B where it was mentioned that a seperated memeory space is allocated for a pointer expression?

And if it is not so and no extra memory is being allocated, then how is the pointer expression stores the value of the base address?

CodePudding user response:

Getting the obvious out of the way, the array is always in the same memory location, it does not change, and you can't move it around, once declared it will occupy the same memory space during its entire existance. No extra memory is needed for this, the only memory needed is for the array elements themselves.

The name of the array is not an element, it is simply for reference and to ease the programming process, it is compiled away, as C does not have reflection it is not needed, the compiler will only need the array address and that's what is kept, it will also know the number of elements and the size of the elements, so you can use sizeof to render the total memory space occupied by it.

The decay process usually happens on assignment or when you pass the array as parameter, what you end up having is a new pointer to the existing array, and the pointer will contain the address of the initial element of the array, that's all.

That pointer has to be stored, and it is, accordingly, deppending on situation, the system knows the size of the pointer, it is implementation defined.

If you use manual memory allocation then the pointer will also have to be stored as well as the memory space for the array, in the heap for the latter.

This also means that you can no longer know the size of the array using sizeof as you can with the array itself, you will be getting the size of the pointer instead.

CodePudding user response:

The conversion is done in the process of evaluating an expression. The original array is not changed. For example, in:

int x = 3;
int y = 4;
int z = x*y   7;

the product of x and y is calculated to be 12, but that is just used in the arithmetic. Neither x nor y is changed.

Similarly, in:

int a[] = { 0, 1, 2, 3 };
int *p = a   2;

the address of the first element of a is calculated by the compiler (based on its knowledge of where a is stored), and a is not changed by this.

  • Related