Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a static and dynamic array

Tags:

c++

c

gcc

icc

friends I was just playing around with some pointer programs and realized that the GCC (and maybe the C standard) differentiates the static and dynamic arrays.

A dynamic array has a place-holder for the address of the elements in the array whereas for the static array, there is no memory location where the compiler stores the starting address of the element array.

I have an example program to demonstrate my confusion.

#include <iostream>
#int main(void)
{
  int _static[10];
  int *_dynamic;

  _dynamic = new int [10];

  std::cout<<"_static="<<_static<<" &_static="<<&_static<<" &_static[0]="<<&_static[0]<<std::endl;
  std::cout<<"_dynamic="<<_dynamic<<" &_dynamic="<<&_dynamic<<" &_dynamic[0]="<<&_dynamic[0]<<std::endl;

  return 0;
}

For the above program, _static and &_static[0] return the same address on the expected lines. However, the &_static also return the same address as the other two.

So, _static and &_static refer to the same number (or address whatever we would like to call it). As expected, _dynamic and &_dynamic indicate different locations.

So, why did the C standard say that _static and &_static must refer to the same location. It sounds confusing. One reason I feel is that &_static does not make much sense. But then should its usage not be reported as an error instead ?

Can somebody please help me with this confusion ?

like image 677
prathmesh.kallurkar Avatar asked Oct 28 '25 08:10

prathmesh.kallurkar


1 Answers

A static array inside a function is allocated on the stack. This way _static (decayed as pointer to the first entry), &_static[0] and &_static have the same value, same memory address.

On the other hand, a dynamic array is in fact a pointer to a contiguous memory area. Only the pointer is stored on the stack. This is why &_dynamic (from the stack) and _dynamic (from the heap) differ.

Hope this image shows it all:

static vs dynamic arrays

Have also a look at this article about static and dynamic global arrays continued with the distinction between extern and non-extern.

like image 56
Mihai Maruseac Avatar answered Oct 29 '25 22:10

Mihai Maruseac