struct array

Hi,
I'm trying to create a struct array like this.

typedef struct NAMELIST
{
char name;
int deviceID;
}; NAMELIST nameList[5];

And fill in the data to it like this.

nameList[0].name = "FIRSTNAME";
nameList[0].deviceID = 0x01;

But now I'm getting this kind of error
error: invalid conversion from 'const char*' to 'char' [-fpermissive]

What I'm doing wrong here?

Thanks

char is a single character, not a whole string

But now I'm getting this kind of error
error: invalid conversion from 'const char*' to 'char' [-fpermissive]

How do you intend for the compiler to store a NULL terminated array of chars in a char variable? That's like trying to put a dozen eggs in one shell.

Aah. You are absolutely right. Sorry about that. I had it like this char name[10];
But still I'm having a problem
error: incompatible types in assignment of 'const char [10]' to 'char [11]'

Got it working with String determination.
Thanks, :slight_smile:

artokang:
Got it working with String determination.

Could you please show me the new working definition of the struct?

Got it working with String determination.

Using the String class is a crutch...don't use it; it uses more memory than need be. Try something like:

typedef struct NAMELIST 
  {
  char name[10];                           // Change
  int deviceID;
  }; NAMELIST nameList[5];

And fill in the data to it like this.

strcpy(nameList[0].name, "FIRSTNAME");     // Change
nameList[0].deviceID = 0x01;

Check your pre/post change file sizes to see how much memory you can save.

1 Like

I would suggest to use

strncpy(nameList[0].name, "FIRSTNAME", 10);

// or, if a 0 char should always be there (init .name[9] = 0 once)

strncpy(nameList[0].name, "FIRSTNAME", 9);

even when using constant strings as source.

Whandall:
I would suggest to use

strncpy(nameList[0].name, "FIRSTNAME", 10);

// or, if a 0 char should always be there (init .name[9] = 0 once)

strncpy(nameList[0].name, "FIRSTNAME", 9);



even when using constant strings as source.

If the array is to be set with initial values at start, I'd not use strcpy or strncpy, but initialize the array like that:

typedef struct NAMELIST {
  char name[10]; 
  int deviceID;
}; 

NAMELIST nameList[5]={
  {"1st name", 1},
  {"2nd name", 2},
  {"3rd name", 3},
  {"4th name", 4},
  {"5th name", 5},
};

In a program which is in need of saving RAM and the strings being constants, I'd also consider to hold the strings as PROGMEM constants instead of using variables in RAM for constant text.

@jurs: I'd agree if the names are known at compile time. I just assumed that was not the case.

If the names are constant, I would suggest using a pointer to a PROGMEM string in the struct,
the fixed length field limits the maximum namelength and wastes space (for all shorter names).

The pointer methode wastes 2 bytes for the counter in each entry.

But als always, you don't get something for nothing.