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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With