Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the attributes of a struct in a 2D array

I have a simple program that makes a 2d array of a struct. I want to know how to manipulate the struct’s attributes. This is my attempt; i keep getting Segmentation fault, the problem happens in the fillarr method;

My problem is that i don’t quite understand how to manipulate the data once it is in a 2D array. I understand that arrays are pointers, my assumption at first was that i could do something like

arr[h][w]->one = 'b';

Which i now know is obviously wrong because the compiler really doesn’t like it.
Now, when i try

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

arr[h][w].one = 'a'

The compiler doesn’t complain about that syntax, but this is where my segmentation fault triggers.

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

struct node {
  char one;
  char two; 
};

typedef struct node node; 

node** makeArr(int h, int w) {
  printf("Making arr\n"); 
  node** output = (node**)malloc(sizeof(node*) * h);

  for (int i = 0; i < h; i++) {
    output[i] = (node*)malloc(sizeof(node) * w); 
  }

  return output; 
}

void killarr(node **arr, int h, int w) {
  printf("Killing arr\n"); 
  for (int i = 0; i < h; i++) {
    free(arr[i]); 
  }
  free(arr);
}

void fillarr(node **arr, int h, int w) {
  printf("Filling arr\n"); 
  char x = 'a'; 
  for (int i = 0 ; i < h; i++) {
    for(int m = 0; m < w; m++){
      arr[h][w].one = x++; // <- here exactly
      
      arr[h][w].two = x++; // <- here too
   
    }
  }
}

int main(int argc, char *argv[]) {
  int h = 10;
  int w = 10; 
  node **arr = makeArr(h, w); 
  fillarr(arr, h, w); 

  killarr(arr, h, w); 
}

>Solution :

Each time through the inner loop you’re accessing arr[h][w]. But since h and w are the array bounds, you’re accessing out of bounds, leading to undefined behavior.

You likely meant:

arr[i][m].one = x++;      
arr[i][m].two = x++;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading