Search code examples
carraysstringtypedefc-strings

How to initialize these array types?


I'm doing a work and I got a bit of code handed to me with some "string" typedef to make use of strings easier, but now I'm having some trouble understanding the code and how it works. Can you guys help me?

//----------- THIS IS THE CODE HANDED TO ME -----------------------------

#define MAX_STRING          256
#define MAX_STRING_VECTOR   1024

typedef char String[MAX_STRING];
typedef String StringVector[MAX_STRING_VECTOR];

//----------- THIS IS THE CODE I WROTE -----------------------------

StringVector strV;
String str;

*str = "Hello";
*(strV) = str;

The error it shows is "assignment to expression with array type".

Thank you guys!


Solution

  • In the C syntax, it is not allowed to assign an array of char, such as str is here, with a string literal except for initializing.

    Rather use strcpy to assign a string to an array. For initializing str by Hello use String str = "Hello";.

    For example:

    StringVector strV;
    String str = "Hello";
    
    strcpy(*strV, str);
    

    Online Example

    Or if str is not needed:

    StringVector strV;
    
    strcpy(*strV, "Hello");
    

    Note: strcpy() is declared in the header <string.h>.