Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify an array of strings from a struct

Tags:

arrays

c

pointers

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.

main.h

typedef struct Person Person;

struct Person
{
    char *names[2];
};

main.c

#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 ?

like image 816
shellwhale Avatar asked Jun 13 '26 02:06

shellwhale


2 Answers

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
like image 146
Serge Ballesta Avatar answered Jun 15 '26 15:06

Serge Ballesta


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"

like image 33
static_cast Avatar answered Jun 15 '26 15:06

static_cast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!