I created a code below, where I need to keep track of an array, increase the pointer to array, and stop if the array ends.
I tested using the code below and apparently after 1000 iterations of increasing ptr
and printing *ptr
, I get 0
as a value.
So is it true the last element of array will ALWAYS be 0? How can I tell the ptr to stop at the last element, if the array length is created dynamicaly (and I am not allowed to use linked list instead)? I am afraid that if I use below code, one day I will meet printf i=1000 , and it returns me random memory location (sofar for the code below, it is not true, but who knows)..
#include <stdio.h>
int my_array[] = {1,23,17,4,-5,100};
int *ptr;
int main(void)
{
int i;
ptr = &my_array[0]; /* point our pointer to the first
element of the array */
printf("value of ptr is %d\n", *ptr);
for(i=0; i<1000; i++){
ptr++;
}
printf("value of ptr is now %d", *ptr);
return 0;
}