Typedef struct with C character array not working

Asked

Viewed 778 times

3

I’m trying to create a kind of constructive data, but I’m having problems 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’t I do x.nome = “ana”;?

1 answer

6


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

You should be used to other languages that copy to you when you do the assignment. In C you have to do at hand.

If the frame was a pointer to char there could put a reference to the literal string. Copying a given scalar (simple) is possible, a compound data needs to be copied. A pointer is scalar. 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks! What would the code look like if it was a char pointer'?

  • 1

    The way you did, only the member would be char *nome

  • 1

    @Paulodossantos more in detail in http://answall.com/q/181609/101.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.