2

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");
danwolb02
  • 41
  • 3
  • Does this answer your question? [Why is this C string assignment illegal?](https://stackoverflow.com/questions/48408235/why-is-this-c-string-assignment-illegal/48408280) [In C, why can't I assign a string to a char array after it's declared?](https://stackoverflow.com/questions/26693537/in-c-why-cant-i-assign-a-string-to-a-char-array-after-its-declared) – KamilCuk Aug 16 '20 at 12:57
  • This [doesn't work](https://tio.run/##bY1NC4JAGITv768Y7FJQkUEnK4iQOpRGGQQRi61bLdga7npJ/O0mfRCUt2dmYB7e4XGozmXZkIrHWSQw1CaK5bF7GRM1InGSSmA52bGVu974Hpv6Wy/AoG7yJkuXLVxvFsxh94i0STNucBOpTpRmmnICtLwLZsCTTBmnyvwSpgBUeBV6/@s57OvvDw4VDpFUBtdQqmYL@Z/tQw69oft0YoT@t3pqqyqHZYQ2ttV@Qd9CJSjK8gE "C (clang) – Try It Online") because the `{...}` thing is meant for initialisation, not assignment, as far as I understand. So `variable = { 2, "whatever" };` is incorrect, because it's assignment, but `struct thing variable = {2, "whatever"};` is initialisation, so it's fine. – ForceBru Aug 16 '20 at 13:00

1 Answers1

0

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.

ACoelho
  • 341
  • 1
  • 11