gpt4 book ai didi

c - 使用 memcpy 时覆盖结构字段

转载 作者:行者123 更新时间:2023-11-30 18:13:34 26 4
gpt4 key购买 nike

我有以下结构和填充它的代码:

typedef struct {
char name[CONTACT_NAME_SIZE];
char surname[CONTACT_SURNAME_SIZE];
char address[CONTACT_ADDRESS_SIZE];
char phoneNumber[CONTACT_PHONENUMBER_SIZE];
} Contact;

...

char buffer[1024];
char phonebookItem[50];

printf("Name (max %d characters): ", CONTACT_NAME_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].name));
strcpy(phonebookContacts[id].name, phonebookItem);

printf("Surname (max %d characters): ", CONTACT_SURNAME_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].surname));
strcpy(phonebookContacts[id].surname, phonebookItem);

printf("Address (max %d characters): ", CONTACT_ADDRESS_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].address));
strcpy(phonebookContacts[id].address, phonebookItem);

printf("Phone number (max %d characters): ", CONTACT_PHONENUMBER_SIZE);
fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].name));
strcpy(phonebookContacts[id].phoneNumber, phonebookItem);

问题是,当我为第一个字段输入数据时,一切正常。但是,当我为下一个字段输入数据时,我输入的所有内容(第一个和第二个输入)都会写入第一个字段,依此类推......

示例:

Name (max 10 characters): 123456789*123456789
phonebookContacts[id].name = 123456789* -> OK
Surname (max 15 characters): 123456789*123456789*
phonebookContacts[id].name = 123456789*123456789*12345
phonebookContacts[id].surname = 123456789*12345

为什么会被覆盖?

最佳答案

而不是这个:

fgets(buffer, sizeof(buffer), stdin);
memcpy(phonebookItem, buffer, sizeof(phonebookContacts[id].name));
strcpy(phonebookContacts[id].name, phonebookItem);

试试这个:

memset(buffer, 0, sizeof(buffer));  // zero out all of buffer
fgets(buffer, sizeof(buffer), stdin); // accept up to n-1 input characters (last zero stays)
strncpy(phonebookContacts[id].name, buffer, CONTACT_NAME_SIZE-1); // copy data

或者:

memset(buffer, 0, sizeof(buffer));  // zero out all of buffer
fgets(buffer, CONTACT_NAME_SIZE, stdin); // accept up to field-specific number of input characters
strcpy(phonebookContacts[id].name, buffer); // copy data

假设缓冲区的大小始终大于您可能提供的任何输入,并且其大小也大于或等于您输入的字段中的最大字段。

编辑:为了清晰起见添加了两个选项

关于c - 使用 memcpy 时覆盖结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com