mathisfun1234
mathisfun1234

Reputation: 71

Pointer arrays and output

I am trying to understand why the output of this code would be 7 11 and I am lost. What is ptr[1][2] and ptr[2][1] referring to?

#include <stdio.h>
#define SIZE 25
int main()
{
    int a[SIZE];
    int *ptr[5];
    
    for (int i = 0; i < SIZE; i++){
        a[i] = i;
    } //has values 0-24
        
    ptr[0]=a; //ptr[0] is assigned with address of array a.
    
    for (int i=1; i < 5; i++){
        ptr[i] = ptr[i-1]+5; //pp[1] = 5; pp[2] = 6??
    }
    printf("\n%d %d",ptr[1][2],ptr[2][1] ); //output is 7 11
    
    return 0;
}

Upvotes: 1

Views: 135

Answers (2)

Paul Spark
Paul Spark

Reputation: 46

ptr[1] = ptr[0]+5 which refer to a[0+5] = a[5]

ptr[2] = ptr[1]+5 which refer to a[5+5] = a[10]

so

prt[1][2] should be a[5+2] which is a[7] = 7

prt[2][1] should be a[10+1] which is a[11] = 11

Upvotes: 2

tadman
tadman

Reputation: 211590

While this is quasi-valid pointer code, it's also not the sort of code you should write in practice because it's going to be quite confusing to keep track of what's going on.

Things like ptr[i-1]+5 is kind of a mess to deal with.

What this does is effectively pluck out values 0, 5, 10, etc. through to 20 and put them into a look-up index of sorts composed of pointers.

Now that you have pointers to a contiguous array you can do sneaky things like ptr[n][i] where that will offset the target by i, but normally you'd just do *ptr[n] to avoid all the extra confusion.

It's worth noting that for simple index lookups it's almost always easier to store offsets than pointers. For example if you had this instead:

int ptr[5];
ptr[0] = 0;

for (int i=1; i < 5; i++) {
  ptr[i] = ptr[i-1]+5;
}

Then later:

printf("\n%d %d",a[ptr[1]],a[ptr[2]]); //output is 7 11

A lot easier to debug, too!

Upvotes: 1

Related Questions