Home > front end >  How to access a 2d array inside a struct using only pointers
How to access a 2d array inside a struct using only pointers

Time:02-23

Trying to understand pointers as a beginner in C- I've got this struct:

    typedef struct {
        int size;           // dimension of array
        int **arr; // pointer to heap allocated array
    } someStruct;

So I use malloc to generate this struct, and an array, and initialize all the values to zero-

someStruct *m = (someStruct*)malloc(sizeof(someStruct));
m->size = n;
m->arr = (int**)malloc(n * sizeof(int));
// initialize array
for (int i = 0; i < n; i  ) {
    *(m->arr   i) = (int*)malloc(n * sizeof(int));
    // set value to 0
    for (int j = 0; j < n; j  ) {
        *(*(m->arr   i)   j) = 0;
    }
}

After this I basically continue to access the array in later stages using the same kind of pointer logic-

for (int i = 0; i < n; i  ) {
    for (int j = 0; j < n; j  ) {
        int num =  *(*(m->arr   i)   j);
        printf("num: %d\n", num);
    }
}

Here's the problem- when I try to use this method of access, I'm clearly not getting the right answer- my print output look like this:

num: -2043774080
num: 22031
num: 0
num: 0
...
num: 0
num: 0

Here's the really weird part- this seeming bug of the 'weird' random numbers only comes when I'm creating and accessing an array of size 5-

I've come to believe that the whole

*(*(m->arr   i)   j)

method of access must be wrong- any help on this would be really useful. Thanks in advance, I apologize if this was already answered, my searching was unable to find it.

CodePudding user response:

You should give complete code, but I think I was able to figure out your intent. You have one glaring problem, and many style issues. Here is what I think your code should look like:

typedef struct {
    int size;           // dimension of array
    int **arr; // pointer to heap allocated array
} MagicSquare;

  :
  :

// no need to dynamically allocate this, it is small
MagicSquare m;
m.size = n;
m.arr = malloc(n * sizeof(int*));  // note it is sizeof(int*), not (int)

// initialize array
for (int i = 0; i < n; i  ) {
    m.arr[i] = malloc(n * sizeof(int));
    // set value to 0
    for (int j = 0; j < n; j  ) {
        m.arr[i][j] = 0;
    }
}

  :
  :

for (int i = 0; i < n; i  ) {
    for (int j = 0; j < n; j  ) {
        printf("num: %d\n", m.arr[i][j]);
    }
}

Note that if you want to initialize the allocated memory to zero, you should just use calloc, which does this initialization for you:

// initialize array
for (int i = 0; i < n; i  ) {
    m.arr[i] = calloc(n,sizeof(int));
}
  • Related