#26 Array of Structures

closed
John Hansen
None
5
2009-01-26
2008-12-03
Carlos Gutierrez
No

I using Bricxcc (NXC/Standar Firmware) to create a global single dimension array of an user define variable.

For instance, I am declaring a struct like this:

struct car
{
int year;
char brand;
};

Then I declare the array:

car MyCar[5];

The problem comes when I try to assign values to the the array. So far, I have tried:

task main()
{
MyCar[2].year=2000;
}

task main()
{
MyCar.year[2]=2000;
}

I am getting a compiler error in each case. What I am doing wrong. Is it possible to define a array of structures?

Discussion

  • I couldn't find the right syntax either. The way I got round this was to define a local variable, set the values on the variable and then assign to the array.

    For exmple

    car MyTmpCar;

    MyTmpCar.year = 2000;
    MyTmpCar.brand = Ford;
    MyCar[0] = MyTmpCar;

    MyTmpCar.year = 2002;
    MyTmpCar.brand = Toyota;
    MyCar[0] = MyTmpCar;

    The Compiler didn't complain. I haven't yet checked whether the array has the correct values.

    I hope this helps
    Duncan Gray

     
  • John Hansen
    John Hansen
    2009-01-26

    • assigned_to: nobody --> afanofosc_99
    • status: open --> closed
     
  • John Hansen
    John Hansen
    2009-01-26

    The NXC compiler does not currently support directly accessing a struct member using the dot syntax following an array index, i.e., MyCar[2].year. Instead, using the current version of the NXC compiler you need to store the element in a variable first and then use the dot notation on that variable.

    Car tmp;
    tmp = MyCar[2];
    tmp.year = 2000;
    MyCar[2] = tmp;

    The standard firmware has a bug in the REPLACE opcode which is used when you try to update an element in an array (the last line in the above code snippet). It definitely breaks multi-dimensional arrays. I'm not 100% sure whether it is okay for arrays of structs. If the array element does not contain the new struct values then you may need to switch to the enhanced NBC/NXC firmware which fixes the REPLACE opcode bug.

    The next version of the NXC compiler will have support for the syntax you tried above (i.e., MyCar[2].year = 2000;).