Typedef struct with C character vector is not working

3

I'm trying to create a constructive data type, but I'm having trouble with the 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 not I x.nome = “ana”; ?

    
asked by anonymous 02.02.2017 / 01:02

1 answer

6

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

You must be accustomed to other languages that do the copy for you when you do the assignment. In C you have to do in hand.

If the structure was a pointer to char there could put a reference to the string . Copying a scalar (simple) die is possible, a given compound needs to be copied. A pointer is to climb. 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 running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
02.02.2017 / 01:14