0

I have two structs.

typedef struct Side Side;

struct Side{
    bool taken;
    unsigned color;
};

typedef struct{
    Side* sides;
}Cube;

I want to make an array of 100 cubes dynamically each with 3 sides - which also needs to be dynamic. What is the proper way of doing this?

void generateCube(Cube** cubes, int size, int (*calculateFunction)(int)){
    *cubes = (Cube*)malloc(sizeof(Cube) * size);
    Cube* cubeIterator = *cubes;
    Cube* endCube = *cubes + sizeof(Cube) * size;
    unsigned sideIndex = 1;

    for(endCube; cubeIterator != endCube; cubeIterator += sizeof(Cube)){
        cubeIterator->sides = (Side*)malloc(sizeof(Side) * 3);

        cubeIterator->sides[0].color = (*calculateFunction)(sideIndex++);
        cubeIterator->sides[1].color = (*calculateFunction)(sideIndex++);
        cubeIterator->sides[2].color = (*calculateFunction)(sideIndex++);
    }
}   

This is what I came up with but the values being assigned to the color are not correct. I am new to C please go easy on me :)

D.H.
  • 186
  • 14
  • 3
    You're going to want to read this: [Pointer Arithmetic](https://stackoverflow.com/questions/394767/pointer-arithmetic). There are two offset calculations in this code (value of `endCube` and loop increment for `cubeIterator`) that use `sizeof`, and both are wrong. Read that question to understand why. Unrelated, [Don't cast malloc in C programs](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Nov 29 '19 at 21:24
  • Thankyou I will! – D.H. Nov 29 '19 at 21:59
  • 1
    If (a) you control the design here and (b) you really always have three sides the you want the cube structure to contain an actual array of sides rather than a pointer to another dynamic allocation. – dmckee --- ex-moderator kitten Nov 29 '19 at 23:01

1 Answers1

0

Thankyou for the comments! I was using pointer arithmetic incorrectly. Here is the updated working code.

void generateCube(Cube** cubes, int size, int (*calculateFunction)(int)){
        *cubes = malloc(sizeof(Cube) * size);
        Cube* iterator = *cubes;
        Cube* end = iterator + size;
        unsigned sideIndex = 1;
        for(end; iterator != end; ++iterator){
                iterator->sides = malloc(sizeof(Side) * 3);

                iterator->sides[0].color = (*calculateFunction)(sideIndex++);
                iterator->sides[1].color = (*calculateFunction)(sideIndex++);
                iterator->sides[2].color = (*calculateFunction)(sideIndex++);
        }
}
D.H.
  • 186
  • 14