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));
}
In the C language, there is no method to determine the size of an unknown array, so the quantity needs to be passed as well as a pointer to the first element.
In C language when you pass the array as an argument to the function , it is automatically converted into pointer ,array passing from one function other function is know as call by reference . That is the reason the called function only receives the pointer which point to the first element of function This is the reason
fun(int a[]) is similar to fun(int *a) ;
so when you print the size of array it will print the size of first element.
So, you will need to pass the lenght of the array as a second parameter. When you are writing code, in which you both declare an array of constant size, and later pass that array to a function, it is a pain to have the array-length constant show up several places in your code...
K&R to the rescue:
So now you can do e.g:
You can't pass arrays to functions.
If you really wanted to print the size, you could pass a pointer to an array, but it won't be generic at all as you need to define the array size for the function as well.
In 'C' programming languange 'sizeof()' is the operator and he returns the size of the object in bytes.Argument of the 'sizeof()' operator must be a left-value type(integer,float number,struct,array).So if you want to know the size of an array in bytes you can do it very simple.Just use the 'sizeof()' operator and for his argument use the array name.For example:
Output on 32 bit system will be: Size of n is: 40.Because ineteger on 32 system is 4bytes.On 64x it is 8bytes.In this case we have 10 integers declared in one array.So the result is '10 * sizeof(int)'.
Some tips:
If we have an array declared like this one 'int n[]={1, 2, 3, ...155..};'. So we want to know how many elements are stored in this array. Use this alghorithm:
sizeof(name_of_the_array) / sizeof(array_type)
Code: #include
main(){
}
The behavior is by design.
Same syntax in function parameter declaration means completely different thing than in local variable definition.
The reason is described in other answers.