#include <stdio.h>
#include <string.h>
struct Directory {
char Name;
long int Number;
int HouseNumber;
char street;
};
int main(void)
{
struct Directory contact;
struct Directory *answer1, *answer2, *answer3, *answer4;
char answer;
printf("Welcome to Telephone Directory.\n\nPlease enter the name of the contact.\n");
scanf("%s", &contact.Name);
printf("Please enter the number of the contact.\n");
scanf("%ld", &contact.Number);
printf("Please enter the address of the contact.\n");
scanf("%d %s", &contact.HouseNumber, &contact.street);
answer1 = &contact;
answer2 = &contact;
answer3 = &contact;
answer4 = &contact;
printf("Would you like to obtain information on your contact? Enter 'yes' or 'no'.\n");
scanf("%s", &answer);
if (strcmp(&answer, "yes")==0) {
printf("%s\n", &answer1->Name);
printf("%ld\n", answer2->Number);
printf("%d", answer3->HouseNumber);
printf("%s", &answer4->street);
}
if (strcmp(&answer, "no")==0) {
printf("Thank you for using Telephone Directory.\n");
}
}
我试图在C中创建联系人程序。我想让程序打印用户的房屋地址。我在结构中有“HouseNumber”变量,在结构中有“street”变量,将“answer3”设置为int变量,以显示“HouseNumber”和“answer4”作为显示“street”的char变量。我一起希望他们能够用一个字符串打印用户的地址,但是当我运行程序并输入“yes”以在进入门牌号和街道后显示联系信息时,程序崩溃,并显示lldb坏线程错误。似乎一切都是正确的,因为我的编译器说代码没有问题,但它崩溃了。有人可以帮助我吗?显示c中的结构的数字和字符串
您的名字必须是长于1个字符。将你的“字符串”设置为char *,或使用字符串库。然后在每个结构中,必须为你的字符串指定malloc大小,并使用结构中的指针指向这个分配的内存。 – Magn3s1um
你的结构是错误的。它包含名称和街道的字符而不是字符串。您应该将其设置为字符数组(即char Name [256])或将其设置为char *指针,然后在分配时使用malloc。 – John