C ++ Array Size

Possible duplicate:
Array size passed as parameter

I'm stupid with this sizeof operator in C ++, you know why it's 4 and 12?

void function (int arg[]) { cout<<sizeof(arg)<<endl; // 4 } int main () { int array[] = {1, 2, 3}; cout<<sizeof array<<endl; // 12 function (array); return 0; } 
+6
source share
4 answers

In main name array is an array, so you get the size in bytes of the array using sizeof . However, the array goes to the pointer when passing the function, so you get sizeof(int*) inside the function.

Remember that accepting an argument in the form of T arg[] exactly matches the argument T* arg . So your function is the exact equivalent

 void function(int* arg) { cout << sizeof(arg) << endl; } 
+23
source
  void function (int arg[]) // or void function (int arg[N]) 

equivalently

  void function (int *arg) 

Thus,

 sizeof(arg) == sizeof(int*) 

If you intend to pass an array, then C ++ offers you to pass it by reference:

 void function (int (&arg)[3]) // ^^^ pass by reference 

Now,

 sizeof(arg) == sizeof(int[3]) 
+4
source

Your next program is similar to the following.

 void function (int arg[]) { cout<<sizeof(arg)<<endl; // 4 } 

The program below prints the size of the pointer.

 void function (int *arg) { cout<<sizeof(arg)<<endl; // 4 } 
0
source

Arrays simply indicate an arbitrary amount of memory. If you make sizeof (an array), it will return the size of the pointer - 4 bytes on 32-bit systems and 8 bytes on 64-bit systems (if the program is compiled as a 64-bit version).

This is the same reason you need to zero out the end of lines in c / C ++ - to mark the end of an array.

Simply put, you yourself track the size of your arrays. If you allocate an array of 40 bytes, you should make sure that you never get access to the array above the 40th index (ie Array [39]).

Hope this helps.

-1
source

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


All Articles