Work with array size

I accidentally asked myself a question about arrays in C ++. Well, we all know that arrays are fixed collections of something, I say it’s fixed, because when defining arrays it is necessary to declare the length of the array. So, consider an example:

char myarray[10] = {'\0'};
int sz = sizeof(myarray); // It is supposed to be 10

Well that's right, 10 is the number returned by sizeof. This can be done by the compiler because it knows how much space it has allocated for this variable.

Now consider what happens in this situation:

void dosome(mystruct* arr) {
   int elements = sizeof(arr)/sizeof(mystruct);
   for (int i = 0; i < elements; i++) {
      // Do something hoping no overflow will ever occur
   }
}

Nice ... but I suppose this could be crowded. If I pass this function an array that I created in the “normal” way, everything should be fine:

mystruct array[20];
dosome(array);

No problems. But if I do this:

mystruct* array = (mystruct*)malloc(80*sizeof(mystruct));
dosome(array);

??????????????????? , sizeof, ??? , , , - , , ? , malloc dosome . ? , sizeof.

.

+3
3
void dosome(mystruct* arr) {
   int elements = sizeof(arr)/sizeof(mystruct);
   for (int i = 0; i < elements; i++) {
      // Do something hoping no overflow will ever occur
   }
}

arr ? mystruct*! , , 4 8. / ( new'd) , , , REFERENCE!

template <int N>
void dosome(mystruct (& arr) [N]) {
    for (int i = 0; i < N; i++) {
      // Do something . No overflow will occur
   }
}

int a[20];
sizof a; //equals to 20*sizeof(int)
int* b = new int [20];
sizeof b; //equals to sizeof pointer, most likely 4 
+1

, mystruct array[20]. , , . mystruct* sizeof(arr).

, , ++ vector s, .

"" - :

template <int N> void somefunction(int (&v)[N]);

EDIT . .

+2

sizeof is a compile time statement. And here it only calculates the size of the pointer.

0
source

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


All Articles