So I understand that I can use the dereferenced value of a pointer as a condition in a for-loop. However, I've been trying to use the location of the pointer (within the array it's pointing at) as the terminating condition.
In other words, when the pointer iterates until the (say third) element of the array that it's pointing at, terminate the loop.
Here is my code below:
int main() {
int *ptr = (int*) calloc(5, sizeof(int));
//returns an int pointer pointing at {0, 0, 0, 0, 0} Correct??
for (int i=0; ptr < ptr 3; ptr , i ){ //i is for counting
*ptr = i 1; // dereference value of each element into 1
printf("value of %d element of ptr is: %d \n", i, *ptr);
}
return 0;
}
I expect the output to be:
value of 0 element of ptr is: 1
value of 1 element of ptr is: 1
value of 2 element of ptr is: 1
However, my code keeps running and outputting until it breaks when reaching a crazy high number (value 1939010 of ptr is: 1939011
).
I'm not sure if I'm misunderstanding pointers or is the problem in my code
CodePudding user response:
This for loop
for (int i=0; ptr < ptr 3; ptr , i ){ //i is for counting
*ptr = i 1; // dereference value of each element into 1
printf("value of %d element of ptr is: %d \n", i, *ptr);
}
is incorrect because it invokes undefined behavior.:) The expression ptr
is evidently less than the expression ptr 3
.
What you need is the following
int i = 0;
for ( int *p = ptr; p < ptr 3; p ){ //i is for counting
*p = i; // dereference value of each element into 1
printf("value of %d element of p is: %d \n", i - 1, *p);
}
That is you need to introduce a new variable of the pointer type that will be incremented in the for loop.