Home > Software engineering >  How to access the attributes of a struct in a 2D array
How to access the attributes of a struct in a 2D array

Time:09-18

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

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); 
}

CodePudding user response:

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  ;
  • Related