mr.loop
mr.loop

Reputation: 1005

Array of pointers whose elements point to another array of pointers

What I need very precisely is an array A[10] and each of its element pointing to the respective element of array B[10] whose each element store its index.

Hence, A[1] points to B[1] and B[1] has value of 1. So, when I call *A[1] or *B[1], I get 1.

I know it can be super easy if the array B[10] is not an array of pointers but of integers but I need this for another purpose.

This is what I did but segmentation fault was offered.

#include <stdio.h>

int main() {
    int *A[10];
    int *B[10];
    
    for(int i=0; i<10; i++) {
        A[i] = B[i];
        *B[i] = i;
        printf("\n%d %d",*A[i],*B[i]);
    }
}

By the way, I am not very proficient in pointers.

Upvotes: 0

Views: 565

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50831

Your commented code :

int main() {
    int *A[10];   // an array of 10 pointers, each of them pointing nowhere
    int *B[10];   // an array of 10 pointers, each of them pointing nowhere

    // now each array a and b contain 10 uninitialized pointers,
    // they contain ideterminate values and they point nowhere
    
    for(int i=0; i<10; i++) {
        A[i] = B[i];     // copy an uninitialized pointer
                         // this usually works but it's pointless

        *B[i] = i;       // you assign i to the int pointed by *B[i]
                         // but as *B[i] points nowhere you end up with a segfault

        printf("\n%d %d",*A[i],*B[i]);  // you never get here because the previous
                                        // line terminates the program with a segfault,
                                        // but you'd get a segfault here too for 
                                        // the same reason
    }
}

Your program is basically equivalent to this:

int main() {
    int *a;     // a is not initialized, it points nowhere
    *a = 1;     // probably you'll get a segfault here
}

Accessing the thing pointed by a pointer is called dereferencing the pointer. Dereferencing an uninitialized pointer results in undefined behaviour (google that term), most likely you'll get a seg fault.

I'm not sure what you're trying to achieve, but you probably want something like this:

#include <stdio.h>

int main() {
  int* A[10];
  int B[10];

  for (int i = 0; i < 10; i++) {
    A[i] = &B[i];
    B[i] = i;
    printf("%d %d\n", *A[i], B[i]);
  }
}

Upvotes: 3

Related Questions