Reputation: 3161
I wish to write an print array function in c. I have herd when you pass an array to a c function via reference it passes a pointer to the first element. I am assuming that I can increment this pointer to iterate over the array however my program just segfaults.
I would like to know firstly why my program is seg faulting and also what the most idiomatic approach to writing a function like this in c. Thanks in adavnce.
void print_array(int *array, int length) {
int i = 0;
for (i = 0; i < length; array++) {
printf("%d\n", *array);
}
}
int main (int argc, int *argv[]) {
int test[10] = {0};
print_array(test, 10);
}
Upvotes: 2
Views: 2320
Reputation: 15632
Your loop is infinite, because i
in i < length
never changes; That condition always evaluates true. As a result, you're jumping past the end of the loop. I suggest changing your loop to:
for (i = 0; i < length; i++) {
printf("%d\n", array[i]);
}
... or, if you wish to use array++
, change the condition:
for (int *end = array + length; array < end; array++) {
printf("%d\n", *array);
}
Upvotes: 4
Reputation: 765
Try this:
void print_array(int *array, int length) {
int i = 0;
for (i = 0; i < length; i++) {
printf("%d\n", array[i]);
}
}
Since i
is your loop control variable (it's in the loop condition), you need to increment it to avoid an infinite loop. And using the []
notation is much easier to grasp for someone at your level than trying to increment the pointer manually.
Upvotes: 0