0

If I declare a simple structure like below:

typedef struct {    
  char name[50];    
  int age;    
} Person;    

struct Person people[7];

And then refer to it below for insertion of data:

static void insert(Person people[HOW_MANY], char *name, int age)    
{    
  static int nextfreeplace = 0;    

  people[nextfreeplace].name = &name;    
  people[nextfreeplace].age = age;     

  nextfreeplace += 1;    
}    

I a get a incompatible type error:

error: incompatible types when assigning to type 'char[50]' from type 'char **' people[nextfreeplace].name = &name;

Have I declared my struct wrong? Or have I messed up my pointers?

Masutatsu
  • 434
  • 1
  • 7
  • 19
  • Take a look at [strncpy](https://linux.die.net/man/3/strncpy) – LPs Nov 02 '16 at 09:26
  • @LPs You probably mean `strcpy`. `strncpy` should be avoided, see [this](http://stackoverflow.com/questions/2114896/why-are-strlcpy-and-strlcat-considered-insecure) and [this](https://randomascii.wordpress.com/2013/04/03/stop-using-strncpy-already/) etc etc. – Lundin Nov 02 '16 at 09:48

1 Answers1

1

Just use

snprintf(people[nextfreeplace].name, 50, "%s", name);

to copy string. In this case it also checks buffer size.

uran235
  • 13
  • 2
  • This worked as intended, but now I get a "array type has incomplete element type" when declaring the struct (e.g. struct Person people[HOW_MANY];). This is surprising, since I put this after the struct declaration, where have I stumbled? – Masutatsu Nov 02 '16 at 09:57
  • You are using typedef in order to define new type Person. Then you should use it exactly (e.g. Person people[HOW_MANY];) – uran235 Nov 02 '16 at 13:12