Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the size of an array parameter the same as within main?

Why isn't the size of an array sent as a parameter the same as within main?

#include <stdio.h>  void PrintSize(int p_someArray[10]);  int main () {     int myArray[10];     printf("%d\n", sizeof(myArray)); /* As expected, 40 */     PrintSize(myArray);/* Prints 4, not 40 */ }  void PrintSize(int p_someArray[10]){     printf("%d\n", sizeof(p_someArray)); } 
like image 473
Chris_45 Avatar asked Dec 29 '09 15:12

Chris_45


People also ask

Why the size of the array Cannot change while the program executes?

If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.

Are array sizes always fixed?

The main difference between Array and ArrayList in Java is that Array is a fixed length data structure while ArrayList is a variable length. You can not change length of Array once create, but ArrayList can re-size itself.

Why do we often need to pass the size of an array as a parameter to a function?

Passing the array size tells the function where the bounds are so you can choose not to go beyond them.

What are 2 typical problems with fixed array sizes?

Because fixed arrays have memory allocated at compile time, that introduces two limitations: Fixed arrays cannot have a length based on either user input or some other value calculated at runtime. Fixed arrays have a fixed length that can not be changed.


1 Answers

An array-type is implicitly converted into pointer type when you pass it in to a function.

So,

void PrintSize(int p_someArray[10]) {     printf("%zu\n", sizeof(p_someArray)); } 

and

void PrintSize(int *p_someArray) {     printf("%zu\n", sizeof(p_someArray)); } 

are equivalent. So what you get is the value of sizeof(int*)

like image 128
13 revs, 3 users 89% Avatar answered Oct 13 '22 14:10

13 revs, 3 users 89%