numberjak
numberjak

Reputation: 1255

Seg fault trying to assign an array of structs in C

I've been away from C for a little bit, so there are some growing pains here.

Basically I'm trying to create an array of all possible RGB values.

#include <stdio.h>

#define MAX 3

struct rgb_val {
    int r;
    int g;
    int b;
};

int main(void) {

  struct rgb_val rgb[MAX];

  int index = 0;
  for (int r = 0; r < MAX; r++) {
    for (int g = 0; g < MAX; g++) {
      for (int b = 0; b < MAX; b++) {
        rgb[index].r = r;
        rgb[index].g = g;
        rgb[index].b = b;
        index++;
      }
    }
  }

  return 0;
}

Upvotes: 1

Views: 261

Answers (4)

GMoney
GMoney

Reputation: 159

I believe you're accessing the array outside of bounds due to increasing the index count beyond MAX.

You would be better off using:

    struct rgb_val rgb[MAX * ((sizeof(rgb_val)/sizeof(int)) * (sizeof(rgb_val)/sizeof(int)))];

    int index = 0;
    for (int r = 0; r < MAX; r++) {
            for (int g = 0; g < MAX; g++) {
              for (int b = 0; b < MAX; b++) {
                rgb[index].r = r;
                rgb[index].g = g;
                rgb[index].b = b;
                index++;
              }
            }
        }

Upvotes: 0

Adam Kotwasinski
Adam Kotwasinski

Reputation: 4554

All right, if you want to assign all possible combinations, then you need 27 of them, not 3 (because 3 possible r/g/b values each).

So you need to have enough entries in your array:

struct rgb_val rgb[MAX * MAX * MAX];

Right now your code is accessing indexes 3, 4, ... 26 of array that is only 3 elements long, hence UB.

Upvotes: 1

Marievi
Marievi

Reputation: 5011

Right now, you access out of your array's bounds, which has size MAX. You need to change your loop to :

int index = 0;
for (int index = 0; index < MAX; index++) {
    rgb[index].r = r;  //some r
    rgb[index].g = g;  //some g
    rgb[index].b = b;  //some b
}

This way, you will access only your array's elements. Now, if you do want to increase the r, g and b's value by one for each struct, all you have to do is

rgb[index].r = index;  
rgb[index].g = index; 
rgb[index].b = index;  

Upvotes: 1

Karthick
Karthick

Reputation: 1000

Accessing array out of bounds.Its an undefined behavior.

Upvotes: 1

Related Questions