I am currently learning about pointers in C programming as part of my training. I am particularly curious about using pointers directly within "for" loops.
For example, in the following "for" loop, how can I directly utilize the ptr variable and observe its value step by step during execution?
#include <stdio.h>
#include <stdlib.h>
int main(){
int x[10]={1,3,2,5,43,67,8,64,22,123};
int* ptr=x;
for(int i=0;i<10;i++){
printf("%d\n",x[i]);
printf("%d\n",*ptr);
ptr++;
}
return 0;
}
I have attempted several solutions, but none have worked as expected. Additionally, I am unsure how to use the ptr variable directly in the "for" loop instead of the loop index i. For example, I would like to restructure my code into the following format.
#include <stdio.h>
#include <stdlib.h>
int main(){
int x[10]={1,3,2,5,43,67,8,64,22,123};
for(int* ptr=x;ptr < 10;ptr++){
printf("%d\n",x[i]);
printf("%d\n",*ptr);
}
return 0;
}
Is it even possible to use pointers in this way?
ptr < 10should beptr < &x[10]ivariable, so you can't usex[i].x+10would be better than&x[10]; although the Standard presently treatsx[i]as syntactic sugar forx+i, semantics would be cleaner and additional optimizations would be facilitated if the syntax&someArray[i]would be limited to yielding addresses strictly withinsomeArray, whilesomeArray+iwas usable to form any address within the containing allocation, or an address "just past" it.for( int* ptr=x; *ptr != -1; ptr++ )