I'm not sure why I cannot use sizeof(array) when passing the array through my function only outputs a value of 1, instead of 1000000. Before passing the array to the function, I printed out the sizeof(array) to get 4000000 and when I try to printout the sizeof(array) in the function, I only get 4. I can iterate through the array in both the function and the main to display all values, I just cannot display sizeof within the function. Did I pass the array through incorrectly?
#include <stdio.h>
#include <stdlib.h>
int
searchMe(int numbers[], int target)
{
printf("%d\n", sizeof(numbers));
int position = -1;
int i;
int k = sizeof(numbers) / sizeof(numbers[0]);
for (i = 0; i < k && position == -1; i++)
{
if (numbers[i] == target)
{
position = i;
}
}
return position;
}
int
main(void)
{
int numbers[1000000];
int i;
int search;
for (i = 0; i < 1000000; i++) {
numbers[i] = i;
}
printf("Enter a number: ");
scanf("%d", &search);
printf("%d\n", sizeof(numbers));
int position = searchMe(numbers, search);
printf("Position of %d is at %d\n", search, position);
return 0;
}
int searchMe(int numbers[], int target)
is equivalent to
int searchMe(int *numbers, int target)
There is a special C rules for function parameters that says parameters of array type are adjusted to a pointer type.
It means in your program that sizeof numbers
actually yields the size of the int *
pointer type and not of the array.
To get the size you have to add a third parameter to your function and explicitly pass the size of the array when you call the function.