【发布时间】:2016-04-04 22:58:12
【问题描述】:
我不明白为什么我的代码会在用户输入数据后打印出垃圾变量。在我的 C 类入门中学习数据结构、链表和内存分配的过程中。感谢您的帮助!
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct AutoMobilesInfo
{
char *Manufacturer, *ModelNameOfCar, *ColorOfCar;
int YearOfCar;
struct AutoMobilesInfo *next;
} Car;
void EnterCarInfo(Car *Info)
{
Info = (Car *)malloc(sizeof(Car));
Info->Manufacturer = (char *)malloc(12 *(sizeof(char)));
Info->ModelNameOfCar = (char *)malloc(12 *(sizeof(char)));
Info->ColorOfCar = (char *)malloc(12 *(sizeof(char)));
printf("Please enter the car's manufacturer: \n");
scanf(" %s", Info->Manufacturer);
printf("Please enter the car's model: \n");
scanf(" %s", Info->ModelNameOfCar);
printf("Please enter the car's color: \n");
scanf(" %s", Info->ColorOfCar);
printf("Please enter the year the car was made: \n");
scanf("%d", &Info->YearOfCar);
}
void PrintedOutCarInfo(Car *host)
{
host = (Car *)malloc(sizeof(Car));
host->Manufacturer = (char *)malloc(12 *(sizeof(char)));
host->ModelNameOfCar = (char *)malloc(12 *(sizeof(char)));
host->ColorOfCar = (char *)malloc(12 *(sizeof(char)));
printf("The car's manufacturer is %s\n", host->Manufacturer);
printf("The car's model is %s\n", host->ModelNameOfCar);
printf("The color of the car is %s\n", host->ColorOfCar);
printf("The year the car was made is %d\n", host->YearOfCar);
}
int main()
{
Car *Car1;
Car1 = (Car *) malloc(sizeof(Car));
EnterCarInfo(Car1);
PrintedOutCarInfo(Car1);
free(Car1);
return 0;
}
【问题讨论】:
标签: c pointers data-structures malloc