I’m trying to pass an entire array to the function but the last value i get is always a garbage value and not 3. Please point out where I’ve made a mistake.
#include<stdio.h>
#include<conio.h>
main() {
int array[3] = {0, 1, 2, 3};
display(&array[0], 3);
}
display(int *j, int n) {
int i;
for(i=0; i<=n; i++) {
printf("\n%d", *j);
j++;
}
}
You cannot pass “an entire array to a function” — C does not do this. Instead, you are passing a pointer to the first element of the array.
mainshould be declaredint main(int argc, char* argv[]). It’s not that horrible to type, and you can even get your text editor to do it for you, if you care enough.You have declared
arrayto contain only three items, but store four items into the array. This should have thrown a compile warning at the least. Pay attention to those warnings. Don’t specify the size of your array unless that size is vital (Say, if you wanted to keep track of US states, thenint states[50] = { ... };might make sense. For now. Maybe this is a bad example.)for(i=0; i<=n; i++)is very often a bug — C array indexes run from0ton-1, not0ton. You’re reading one-past-the-array, and that value is not surprisingly garbage.Further this code is awkward; you should just use
printf("\n%d", j[i])and not incrementjeach time. Incrementing two variables as “loop variables” this way is a recipe for writing bugs in the future. (If you need to update two variables with every loop iteration, place both in the last section of thefor(;;i++, j++)loop.)