In the program below the length of the array ar
is correct in main but in temp
it shows the length of the pointer to ar
which on my computer is 2 (in units of sizeof(int)
).
#include <stdio.h> void temp(int ar[]) // this could also be declared as `int *ar` { printf("%d\n", (int) sizeof(ar)/sizeof(int)); } int main(void) { int ar[]={1,2,3}; printf("%d\n", (int) sizeof(ar)/sizeof(int)); temp(ar); return 0; }
I wanted to know how I should define the function so the length of the array is read correctly in the function.
Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.
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.
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. 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]);
To count the duplicates in an array:Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
There is no 'built-in' way to determine the length inside the function. However you pass arr
, sizeof(arr)
will always return the pointer size. So the best way is to pass the number of elements as a seperate argument. Alternatively you could have a special value like 0
or -1
that indicates the end (like it is \0
in strings, which are just char []
). But then of course the 'logical' array size was sizeof(arr)/sizeof(int) - 1
Don't use a function, use a macro for this:
//Adapted from K&R, p.135 of edition 2. #define arrayLength(array) (sizeof((array))/sizeof((array)[0])) int main(void) { int ar[]={1,2,3}; printf("%d\n", arrayLength(ar)); return 0; }
You still cannot use this macro inside a function like your temp
where the array is passed as a parameter for the reasons others have mentioned.
Alternative if you want to pass one data type around is to define a type that has both an array and capacity:
typedef struct { int *values; int capacity; } intArray; void temp(intArray array) { printf("%d\n", array.capacity); } int main(void) { int ar[]= {1, 2, 3}; intArray arr; arr.values = ar; arr.capacity = arrayLength(ar); temp(arr); return 0; }
This takes longer to set up, but is useful if you find your self passing it around many many functions.
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