Problem with C ++ dynamic array

The main pseudo code is as follows:

void myFunction()
{

int size = 10;

int * MyArray;

MyArray = new int[size];

cout << size << endl;

cout << sizeof(MyArray) << endl;

}

The first cout returns 10, as expected, while the second cout returns 4.

Does anyone have an explanation?

+3
source share
5 answers

MyArray - this is just a pointer that is four bytes in size on your system.

When you dynamically create an array, you need to track the size yourself.

If you created an automatic array or a static array,

int MyArray[10];

then it sizeof(MyArray)will be 40. As soon as the array decays to a pointer, although, for example, when you pass it to a function, size information is lost.

+8
source

Related to a recent question.

- , , . . std::vector.


sizeof , int*. , .

:

int i = 0;
i = 23434634;

, i , i sizeof(i) == sizeof(int). , .

+2

MyArray int*. sizeof() .

, (.. int MyArray[3];).

0

MyArray - int*, sizeof(int*) - 4.

MyArraynot an array. This is a pointer that points to the memory block in which you allocated the array.

int MyArray[10];
cout << sizeof(MyArray) << endl;

This should print 40, which is a large 10 inton your system. In this case MyArray, it is an array. Thus, the size of this type includes the size of all elements of the array.

MyArray in this second case it will decay to a pointer, but they are still two different types.

0
source
#include <iostream>

#define P(expr) std::cout << #expr << " = " << (expr) << std::endl

namespace {
  void myFunction(size_t size) {
    int *pointer = new int[size]; 
    int MyArray[size];

    P(size);
    P(sizeof(MyArray));
    P(sizeof(pointer));

    delete [] pointer;    
  }
}
int main() {
  myFunction(10);
}

Conclusion:

size = 10
sizeof(MyArray) = 40
sizeof(pointer) = 8
0
source

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


All Articles