Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of array in c

Tags:

arrays

c

size

a simple question that bugs me. Say I have an array defined in main like so int arr[5]. Now, if I'm still inside main and I set int i = sizeof(arr)/sizeof(arr[0]) then I is set to be 5, but if I pass the array as a function parameter and do the exact same calculation in this function, I get a different number. Why is that? At first I thought its because in a function arr is a pointer, but as far as I know arr is a pointer inside main too!

Also, if I do something very similar only I initialize the array dynamically, I get weird results:

int *arr = (int*) malloc(sizeof(int) * 5);
int length = sizeof(*arr) / sizeof(arr[0]);
printf("%d\n",length);

Here the output is 1. Any ideas why? Thanks in advance!

like image 322
yotamoo Avatar asked Sep 25 '11 12:09

yotamoo


People also ask

How do you find the size of an array in C?

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]);

What is the size of an array?

The theoretical maximum Java array size is 2,147,483,647 elements. To find the size of a Java array, query an array's length property. The Java array size is set permanently when the array is initialized. The size or length count of an array in Java includes both null and non-null characters.

How do you find the size of an array?

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.

What is sizeof () in C?

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.


2 Answers

This is because arr is now a pointer and it could point to a single int or an array of 1000 ints the function just does not know. You will have to pass the size of the array into the function.

In main arr is declared as an int[5] and so the size can be calculated by the compiler.

like image 26
mmmmmm Avatar answered Oct 10 '22 01:10

mmmmmm


C arrays don't store their own sizes anywhere, so sizeof only works the way you expect if the size is known at compile time. malloc() is treated by the compiler as any other function, so sizeof can't tell that arr points to the first element of an array, let alone how big it is. If you need to know the size of the array, you need to explicitly pass it to your function, either as a separate argument, or by using a struct containing a pointer to your array and its size.

like image 152
Staven Avatar answered Oct 09 '22 23:10

Staven