Assign values to string array in C

Viewed 67

I have a struct that looks like this:

struct persons_s
{
  size_t count;
  char   names[MAX_PERSON_COUNT][MAX_PERSON_NAME_LENGTH];
};

When I try to assign values like this, it does not work:

struct persons_s persons;
persons.count = 2;
persons.names = { "test1", "test2" };

But this works:

struct persons_s persons = { 2, { "test1", "test2" } };

I am assuming this has something to do with the names array being constant, but I'm not sure.

So I'm asking:

  1. What is the exact reason the first way does not work?
  2. Is there a better way to accomplish this?

I also tried

char *names[MAX_PERSONS_COUNT];

but this doesn't work either because I have to use it with strcpy (as destination, strcpy(persons.names[i], source);).

Currently I am doing the assignment like this (using the first struct):

struct persons_s persons;
persons.count = 2;
strcpy(persons.names[0], "test1");
strcpy(persons.names[1], "test2");
1 Answers

You are trying to assign a constant to a pointer (char[][], or **char), in C a string is an array of chars, you can either use strcpy or make it yourself with a for loop.

Your way strcpy(persons.names[0], "test1"); works fine and is probably the best option for you.

Related