Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does c++ store the size of fix sized array?

This problem is a follow up from Declaring array of int

Consider the following program:

#include <iostream>
#include <string>

int main()
{
  int x[10];
  std::cout << sizeof(x) << std::endl;
  int * y = new int [10];
  std::cout << sizeof(y) << std::endl;
  //delete [] y;
}

sizeof(x) prints 40 (total size), sizeof(y) prints 8 (pointer size)

It looks interesting, to me int x[10] is no different than y except it is located in the stack. Where does c++ actually stored the size of x? Does c++ get it from the stack? Or a fix sized array is treated as a struct with size internally?

like image 461
James Maa Avatar asked Jan 04 '23 10:01

James Maa


1 Answers

The size of an array doesn't need to be stored, the compiler itself knows how big it is because it's part of the type.

When you dynamically allocate an array as you did with y in your example, the size of the array does need to be stored somewhere so that delete[] can do the right thing. But this is an implementation detail that isn't accessible to the program.

like image 194
Mark Ransom Avatar answered Jan 05 '23 23:01

Mark Ransom