0

I'm trying to print the array index using pointers arithmetic. Does anyone have any idea how to do it? in particular "j" I would like you to do it.

#include <stdio.h>

int main(void) {

    int b[10] = {2, 8, 4, 7, 1, -45, 120, 78, 90, -6};
    int *pb, j = 0;

    for(pb = &b[0]; pb < &b[10];) {
        printf("[%d] = %d\n", j, *pb++);
    }

    return 0;
}
1
  • 1
    well you could also do j++ in the loop Commented Oct 28, 2019 at 8:45

2 Answers 2

2

Like this:

int main(void) {

    int b[10] = { 2, 8, 4, 7, 1, -45, 120, 78, 90, -6 };
    int *pb, j = 0;

    for (pb = &b[0]; pb < &b[10]; pb++) {
        printf("[%td] = %d\n", pb-b, *pb);
    }

    return 0;
}

In pointer arithmetic you can get the index difference with subtraction: pb-b is the index of the element that b points to in array pb. I also moved the *pb++ to the for loop increment in order to avoid an off-by-one-error.

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

Comments

1

Here is another option:

int b[10] = {2, 8, 4, 7, 1, -45, 120, 78, 90, -6};
for (int* pb = b; pb != b + sizeof(b) / sizeof(*b); pb++)
    printf("[%d] = %d\n", pb - b, *pb);

3 Comments

I tried to execute the code but I get this error: warning: format specifies type 'int' but the argument has type 'long' [-Wformat] printf("[%d] = %d\n", pb - b, *pb); ~~ ^~~~~~ %ld I have a change %d with ld... why does it need a long decimal?
@RobertoRocco: Because on your platform, it is possible that the size of a pointer is 64 bits, in which case, pb - b yields a 64-bit value, which should be printed via %ld. Since we know that pb - b is at most 10, you can cast it to int and keep the %d%, o in other words: printf("[%d] = %d\n", (int)(pb - b), *pb);.
In fact, even if the size of pointer on your platform is 32 bits, the compiler might be configured to a very restrictive level, where a pointer should be treated as long int. In any case, you can check pointer size of your platform via sizeof(void*).

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.