简体   繁体   中英

C character pointers

So I have a struct in C

struct LData {
    char* name;
    int age;
    int sex; /* 0 = male, 1 = female */
};

Thats created with

struct LData *create_data(char *name, int age, int sex) {
    struct LData *data;

    data = malloc(sizeof(struct LData));
    data->name = name;
    data->age = age;
    data->sex = sex;

return data;
}

And I try and print this information using

void print_data(struct LData *data) {
    char *sex;

    if (data->sex == 0) {
        sex = "male";
    } else {sex = "female";}
    printf("%c-%d-%c",data->name, data->age, *sex);
}

But I keep getting this formating error:

listdata.c: In function _print_data_:
listdata.c:52:2: warning: format _%c_ expects argument of type _int_, but argument 2 has type      _char *_ [-Wformat=]
printf("%c-%d-%c",data->name, data->age, *sex);

I know something is messed up with my *name pointer, but I can't quite pin point it.

对于字符串(指向char的指针),您需要%s而不是%c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM