我试图指向结构中包含的字符串中的指定字符
这是我的密码

typedef struct{
    char *name;
    int age;
}PERSON, *person;

int main(){
    person serenity;
    serenity = (person)malloc(sizeof(PERSON));
    strcpy(&(serenity->name),"Serenity");
   printf("%c",*(&(serenity->name)+1));
}

在这里,我想显示第二个字符“e”,但它显示的是“n”
任何人都能解释我这是怎么回事,
谢谢您

最佳答案

您尚未为name分配内存

typedef struct{
    char *name;
    int age;
}PERSON, *person;

int main(){
    person serenity;
    serenity = malloc(sizeof(PERSON));
    serenity->name = malloc(sizeof("Serenity")); //<< Missing
    strcpy((serenity->name),"Serenity");
    printf("%c",*((serenity->name)+1)); // << Also you want the value in pointer name NOT its address
    return 0;
}

输出e。另外,由于您标记了C,因此不需要强制转换malloc的返回类型。

10-06 07:41