Page 1 of 1

Using structs with arrays

Posted: 25 Jun 2012, 18:03
by elendurwen
Hi, I want to use an array of structs where each struct can have an array of integers. I can set the values of everything ok, but when I try to access the values I get a crash and 'File error! -1' displayed on the screen.

The struct looks like this:

Code: Select all

struct SensorHandler {
    int id;
    int cellTargetIds[2];
    byte port;
};
Then I initialise it all:

Code: Select all

    //-- create empty array:
    SensorHandler emptyHandler;
    ArrayInit(sensorHandlers,emptyHandler,NUM_OF_SENSORS);
    
    //-- init all index-specific vals:
    for (int i=0; i<NUM_OF_SENSORS; i++) {
        for (int j=0; j<2; j++) {
            sensorHandlers[i].cellTargetIds[j] = -1;
        }
        sensorHandlers[i].cellTargetIds[0] = i;
    }

And later in the code:

Code: Select all

   for (int i=0; i<NUM_OF_SENSORS; i++) {
        for (int j=0; j<1; j++) {
            NumOut(0,0,sensorHandlers[i].cellTargetIds[0]); //THIS LINE CAUSES THE PROGRAM CRASH
        }
  }

I have also tried assigning the cellTargetIds[0] to an int variable with the same result. Any ideas anybody? Has anyone used structs like these successfully?

Re: Using structs with arrays

Posted: 07 Jul 2012, 21:28
by afanofosc
Complex data structures such as arrays of structs that contain arrays has been known to result in peculiar errors such as this. However, in this case, the problem is probably caused by the fact that you are initializing your array with a struct instance that has no members in its nested array. NXC does not currently automatically size arrays in structure declarations. It ignores the size in the declaration. So you need to initialize it manually using ArrayInit or by assigning an already allocated array to the struct member.

Try initializing the emptyHandler struct's array before you use it to initialize the array of structs.

Code: Select all

SensorHandler emptyHandler;
ArrayInit(emptyHandler, 0, 2); // put 2 zeros into the struct that we use to initialize our array
ArrayInit(sensorHandlers,emptyHandler,NUM_OF_SENSORS);
I do not know how the code that you use to inialize the array could execute without errors.

John Hansen

Re: Using structs with arrays

Posted: 30 Jul 2012, 13:52
by afanofosc
My example code was wrong. I forgot to include the struct member.

Code: Select all

SensorHandler emptyHandler;
ArrayInit(emptyHandler.cellTargetIds, 0, 2); // put 2 zeros into the struct that we use to initialize our array
ArrayInit(sensorHandlers,emptyHandler,NUM_OF_SENSORS);
John Hansen