I usually deal with array of strings this way, because it allow me to not specify a character limit :
char *names[2] = {"John","Doe"};
printf("%s\n",*((names)));
printf("%s\n",*((names)+1));
I am unable to reproduce this while using a struct.
I tried with both john.names = {"John","Doe"}; and john.*names = {"John","Doe"}. But I am getting an expected expression error.
However, I am able to do so during the initialization with Person john = {{"John","Doe"}};. So I'm not sure if it's allowed to proceed like this only during initialization.
typedef struct Person Person;
struct Person
{
char *names[2];
};
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
int main()
{
Person john = {{"John","Doe"}};
john.names = {"John","Doe"}; // Expected expression error
printf("%s\n",john.names[0]);
printf("%s\n",john.names[1]);
return 0;
}
What would be the "expected expression", am I allowed to do this ?
Arrays are not first class elements in C. You can initialize a full array, but you can only assign to non array elements, meaning scalars, pointers or structs.
When you write
char *names[2] = {"John","Doe"};
, it is an initialization, not an assignment. And the following assignment would also choke with a syntax error:
char *names[2];
names = {"John","Doe"}; // syntax error here
For initialization of a specific field/attribute, you can do something like the following during declaration:
Person john = {.names = {"John","Doe"}};
To initialize additional fields, let's say address and names, this can be done like the following:
Person john = {.names = {"John","Doe"}, .address="foo"};
After declaration, you will have to specify the array index.
john.names[0] = "John"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With