我试图在C中创建一个链表,这篇文章指的是我尝试在结构中为用户输入的字符串值分配变量的部分.如果我使用strcpy()而不是strdup()然后我得到不需要的输出,程序编译完美.
该程序编译良好,不会发出警告或错误.如果使用strdup(),那么程序按预期工作,但我想知道为什么当使用strcpy()时它不起作用.当传递名称的字符串时,当列表被打印时,它偶尔会打印null然后终止,或者它将打印"Name:Name:Name:Name:Nam"或其他不可预测的错误.任何其他评论或批评将不胜感激,我只是开始学习语言,谢谢.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct addressBook {
char *name;
int age;
char *phoneNumber;
struct addressBook *next;
};
static struct addressBook *head = NULL;
static struct addressBook *current;
static struct addressBook *createNew;
//function prototypes
void addNode(void);
struct addressBook * createNode(void);
void printAddressBook(void);
void printStats(void);
int main(void)
{
addNode();
addNode();
printAddressBook();
addNode();
addNode();
printAddressBook();
}
struct addressBook * createNode(void)
{
struct addressBook *newNode;
newNode = (struct addressBook *) malloc(sizeof(struct addressBook));
if (newNode == NULL)
{
puts("Memory error");
exit(1);
}
printf("\nEnter persons name: ");
char name[20];
scanf("%s", name);
strcpy(newNode -> name, name); //produces unpredictable results
//newNode -> name = strdup(name); Works fine with strdup
printf("Enter persons age: ");
scanf("%d", &newNode -> age);
printf("Enter persons phone number: ");
char phoneNumber[15];
scanf("%s", phoneNumber);
strcpy(newNode -> phoneNumber, phoneNumber); //produces unpredictable
results
//newNode -> phoneNumber = strdup(phoneNumber); Works fine with strdup
return(newNode);
}
void addNode(void)
{
createNew = createNode();
current = createNew;
current -> next = head;
head = current;
}
void printAddressBook(void)
{
struct addressBook *temp;
temp = head;
while(temp)
{
printf("Name: %s\nAge: %d\nPhoneNumber: %s\n\n\n",
temp -> name,
temp -> age,
temp -> phoneNumber);
temp = temp -> next;
}
}
Run Code Online (Sandbox Code Playgroud)
当您定义指针时,char *name;它指向某个随机位置,因为您尚未初始化它.写入指针是违法的,这样做会调用未定义的行为.
strcpy基本上将字符串写入调用UB的此随机指针位置.
strdup另一方面,为字符串动态分配所需的内存,将字符串复制到该位置,然后返回该位置的开头.您可以读/写此内存位置,因此这是有效的.