I'm programming with the C language and I need to count how many elements are in the array to use further in the program.
Most online answers have arrays with like terms (Ex: 55, 66, 77) but my array will consist of random numbers.
An example of my array would be (4, 6, 77, 450, 0, 99).
The code i'm currently using to count the size is as follows, but the code doesn't work when 0 is an element of the array.
int size = 0;
while(*(arr+size) != '\0'){
size++;
}
And, I also tried to use sizeof
but it also doesn't work. See the complete program below.
#define MAX 20
void display(int *arr);
main(int argc, char *argv[]) {
int array[MAX], count;
/* Input MAX values from the keyboard. */
int i; count=0;
while ( scanf("%d", &i) != EOF){
*(array + count) = i; // store in array[count]
count++;
}
/* Call the function and display the return value. */
printf("Inputs: ");
display(array);
return 0;
}
/* display a int array */
void display(int *arr) {
int size = 0;
int s2 = sizeof(arr)/ sizeof(arr[0]);
printf(" -- %d -- ", s2);
while(size <= s2){
printf("%d ", *(arr+size));
size++;
}
}
display
is the function that is trying to count the elements in the array. s2
always returns value of 2, which is incorrect.
How can I count the elements of the array?