Typedef struct with character vector in C is not working

I'm trying to create a constructive data type, but I'm having trouble with strings.

   typedef struct {
        char nome[30];
        int idade;
    } p;

    p x,y; 

    x.nome = “ana”;
    x.idade = 20;
    y.nome = “caio”;
    y.idade = 22;

    printf(“%s : %d”, x.nome, x.idade);
    printf(“%s : %d”, y.nome, y.idade);

Why can't I do x.nome = “ana”;?

Author: Maniero, 2017-02-02

1 answers

You need to use strcpy() to copy the contents of the string into the structure on the member where the array of char has reserved space.

You should be used to other languages that do the copying for you when you do the assignment. In C you have to do on hand.

If the structure was a pointer to char then you could put a reference to the literal string. Copying a scalar (simple) data is possible, a compound data needs to be copied. A pointer is to scale. A string is composed.

#include <stdio.h>
#include <string.h>

typedef struct {
    char nome[30];
    int idade;
} p;

int main(void) {
    p x,y; 
    strcpy(x.nome, "ana");
    x.idade = 20;
    strcpy(y.nome, "caio");
    y.idade = 22;
    printf("%s : %d", x.nome, x.idade);
    printf("%s : %d", y.nome, y.idade);
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 6
Author: Maniero, 2020-11-23 20:22:47