Where does C ++ store size array size?

This problem is the result of declaring an int array.

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 seems interesting to me, for me int x[10]it is no different from y, except that it is on the stack. Where does C ++ actually store the size x? Does C ++ get it from the stack? Or is a fixed-size array considered a structure with a size inside?

+4
source share
3 answers

You have two different types:

int x[10];

Declares a type int[10]. As you can see, the size of the array is part of the type.

int * y;

int. , . , 64- ( ).


, ++ 17:

template<class T>
std::enable_if_t<std::is_pointer_v<T>> foo(T ptr)
{
    std::cout << "Called foo for a pointer type" << std::endl;
}

template<class T, int N>
void foo(T (&arr)[N])
{
    std::cout << "Called foo for an array type of size " << N << std::endl;
}

foo. , , ( ).

main:

int x[10];
int * y = nullptr;
foo(x);
foo(y);

, :

foo 10
foo

Runnable code


: Mark Ransom , y, . , , (, malloc new) , . , delete, , ; (free delete) , . , , , 1 , 1 . ( , , )

+3

, , , .

, y , -, delete[] . , .

+4

++- ( ). , sizeof() .

, .

, ( ). delete[] , .

+2

Source: https://habr.com/ru/post/1686231/


All Articles