How does this code snippet work?
The code is just very simple, yet I scratch my head at the results. I am just playing pointer arithmetics and 开发者_如何学运维want to print out the array but I get the numbers of the array plus 3 more. Where do those 3 extra come from ?
#include <stdio.h>
int my_array[] = {1,3,5,6,73,343,34};
int *pointer_numeros;
int main (void) {
int i = 0;
pointer_numeros = my_array;
while(*pointer_numeros) {
printf("los numeros del array son %d\t %d\n\n", i++, *pointer_numeros++);
}
getchar();
return 0;
}
*pointer_numeros
does not evaluate to false at the end of the array; it will carry on walking through memory until it hits an address whose contents are zero (but this is undefined behaviour).
You can terminate your array in a zero, as others have suggested. But in general, you will still have a problem: what if some of your elements are themselves zero?
Did you mean to write:
int my_array[] = {1,3,5,6,73,343,34,0};
?
Your code iterates until it finds a zero in the array. Your array has no zero in it.
Your loop will only stop when it sees the pointer pointing at 0. Fix it like this:
int my_array[] = {1,3,5,6,73,343,34,0};
精彩评论