2

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?

5
  • 1
    You're close: ptr < 10 should be ptr < &x[10] Commented Feb 12 at 18:47
  • 1
    You also got rid of the i variable, so you can't use x[i]. Commented Feb 12 at 18:47
  • 3
    I think x+10 would be better than &x[10]; although the Standard presently treats x[i] as syntactic sugar for x+i, semantics would be cleaner and additional optimizations would be facilitated if the syntax &someArray[i] would be limited to yielding addresses strictly within someArray, while someArray+i was usable to form any address within the containing allocation, or an address "just past" it. Commented Feb 12 at 18:55
  • if using gcc , compile with -Wall -Wextra -Wpedantic -std=c11 and see what messages are spat out (if any). Commented Feb 12 at 23:39
  • Better use counter to 10 or set unused value for final element, e.g. -1 for( int* ptr=x; *ptr != -1; ptr++ ) Commented Feb 13 at 8:26

4 Answers 4

2

For starters the header <stdlib.h> is redundant in your program because neither declaration from the header is used in your program.

It would be better to declare the array x without specifying the number of its elements. In this case your program will be more flexible. It will be enough just to change the number of its initializers if you will want to add or remove some elements from the array in its declaration.

And do not use magic numbers as 10 used in your for loop. Using magic numbers makes programs error prone.

As for your this for loop

for(int* ptr=x;ptr < 10;ptr++){

then in the condition of the loop you are trying to compare the address stored in the pointer ptr with the magic integer value 10 that does not make sense.

And in general declare pointers with qualifier const if you are not going to change data pointed to by pointers.

The program can look the following way.

#include <stdio.h>

int main( void )
{
    int x[] = { 1, 3, 2, 5, 43, 67, 8, 64, 22, 123 };
    const size_t N = sizeof( x ) / sizeof( *x );

    for ( const int *first = x, *last = x + N; first != last; ++first )
    {
        printf( "%d ", *first );
    }
    putchar( '\n' );

    return 0;
}

Inside the for loop the pointer last points to the memory after the last element of the array due to the pointer arithmetic used in the expression x + N. So when the pointer first will traverse all elements of the array it will be equal to the pointer last and the loop will be ended.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this version.

#include <stdio.h>

int main() {
  int x[10] = { 1,3,2,5,43,67,8,64,22,123 };

  for (int* ptr = x; ptr < x+10; ptr++) {
    printf("The value at %p is %d\n", (void*) ptr, *ptr);
  }
  return 0;
}

ptr stops when it's 10 elements further than when it started (starts at x, ends at x+10).

Each time we print what ptr itself is, the address (the void* cast is there to adhere to C standard -- doesn't affect the logic of the program) and also print the element it will produce.

Here's my output (your pointers will differ, but not the values):

The value at 000000BBA258F928 is 1
The value at 000000BBA258F92C is 3
The value at 000000BBA258F930 is 2
...

We can't use x[i] because i doesn't exist, but that's fine, because ptr does and get us the values we want.

3 Comments

Good catch on %p! Do I really need to cast to void* as well?
Yes if you want to be 100% correct and portable you need the (void*), but actually you will get away without it on most platforms. Read this for the gory details.
Got it! Fix applied.
0

hmmmmmmmm....

    for(int* ptr=x;ptr < 10;ptr++){
        printf("%d\n",x[i]);
        printf("%d\n",*ptr);
    }

wrong!!!! yoou can do the following, instead:

    for(int* ptr=x;ptr < x + 10;ptr++){
        /* printf("%d\n",x[i]); in this case you don't have i */
        printf("%d\n",*ptr);
    }

Don't worry, as x + 10 is a constant pointer in the context of the loop and will not have to be calculated on each iteration. Indeed, that code is equivalent to this:

    const int * const x_end = x + 10; /* get x_end before entering the loop */
    for(int* ptr=x;ptr < x_end;ptr++){
        printf("%d\n",*ptr);
    }

Comments

-1

The code you are intending to will not work

you have initialized the variable ptr as a pointer inside the for loop and in the ptr you stored the x ,here (in c) x is an array and it will contain the starting address of the array which is also a pointer so

but when you start to compare the ptr with 10 which will create an error logically since the value a pointer will have value of 64000,6784579,.....etc the program will consider this pointer as an integer perform comparison . due to this conidering the value of ptr exceeded the 10 the for loop will be exited

and the i you are using is not defined

the program i given below uses your idea to print the array's elements using a pointer the base value is incremented by the 1 integer each time which will give you each element sequentially similary to using a pointer loop

#include <stdio.h>
#include <stdlib.h>

int main(){
    int x[10]={1,3,2,5,43,67,8,64,22,123};

    for( int ptr=0;ptr < 10;ptr++){
        printf("%d\n",*(x+ptr));
    }
    return 0;
}

3 Comments

You've got a variable here named ptr which is declared as an int. You can certainly use an int here, but OP wants to know about pointers.
I think the OP wanted to learn about pointers so your approach (while valid) might not help too much.
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.