C 语言 结构体指针-误区

typedef struct _BOOK
{
char * name;
char * author;
float price;
} BOOK;
void initBooks(BOOK * pBooks, int count)
{
char * name;
char * author;
float price;

for (int i = 0; i < count; i++) {
    //开辟书信息的内存空间
    printf("请输入第%2d本数的信息:  书名  作者  价格\n", i);

    name = (char *)malloc(sizeof(char) * 100);
    author = (char *)malloc(sizeof(char) * 100);
    scanf_s("%s %s  %f", name, 100, author, 100, &price);
    printf("你的输入是:%s %s  %f\n", name, author, price);
    pBooks[i].price = price;
    system("pause");
    pBooks[i].name = name;
    pBooks[i].author = author;
    strcpy_s(pBooks[i].name,  100, name); //此处报错,.name是一个空的地址
    strcpy_s(pBooks[i].author, 100, author);        
}

}
//error
int main()
{
BOOK * pBooks;
int count;
printf("请输入要保存的书籍数量\n");
scanf_s("%d", &count);
pBooks = (BOOK * )malloc(sizeof(BOOK) * count);
initBooks(pBooks, count);

for (int i = 0; i < count; i++) {
    printf("%2d  %s %s %d\n", i, pBooks[i].name, pBooks[i].author, pBooks[i].price);
}
system("pause");

}

你可能感兴趣的:(C 语言 结构体指针-误区)