Possible Duplicate:
Sizeof an array in the C programming language?
Why does a C-Array have a wrong sizeof() value when it's passed to a function?
See the below code and suggest me that what is the difference of "sizeof" keyword when I used like this:
#include<stdio.h> #include<conio.h> void show(int ar[]); void main() { int arr[]={1,2,3,4,5}; clrscr(); printf("Length: %d\n",sizeof(arr)); printf("Length: %d\n",sizeof(arr)/sizeof(int)); show(arr); getch(); } void show(int ar[]) { printf("Length: %d", sizeof(ar)); printf("Length: %d", sizeof(ar)/sizeof(int)); }
But the output is like this:
Output is:
Length: 10
Length: 5
Length: 2
Length: 1
why I am getting like this; If I want to take the entire data from one array to another array the how can I do?
Suggest me If anyone knows.
To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers.
The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function.
Arrays decay to pointers in function calls. It's not possible to compute the size of an array which is only represented as a pointer in any way, including using sizeof
.
You must add an explicit argument:
void show(int *data, size_t count);
In the call, you can use sizeof
to compute the number of elements, for actual arrays:
int arr[] = { 1,2,3,4,5 }; show(arr, sizeof arr / sizeof *arr);
Note that sizeof
gives you the size in units of char
, which is why the division by what is essentially sizeof (int)
is needed, or you'd get a way too high value.
Also note, as a point of interest and cleanliness, that sizeof
is not a function. The parentheses are only needed when the argument is a type name, since the argument then is a cast-like expression (e.g. sizeof (int)
). You can often get away without naming actual types, by doing sizeof
on data instead.
Thats the reason why, when writing a function that takes an array, two parameters are declared. one that is a pointer to the array, the other that defines the size of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With