所以我试着编写这段代码并用结构测试一些东西..它编译但是当我到达" scanf("%d",sp [i] .cylinder);"当我给scanf一个int输入时,exe崩溃了。我错过了一些明显的东西吗?
#include <stdlib.h>
#include <stdio.h>
struct car {
char name[20];
char company[20];
int cylinder;
int year;
int plates;
};
struct car *sp;
void function();
int main() {
int maxcars=3;
printf("Give number of cars \n");
//scanf("%d", &maxcars);
function(maxcars);
printf("There are %d cars\n", maxcars);
int i;
for(i = 0; i < maxcars; i++){
printf("%s\n", i, sp[i].name);
printf("%s\n", i, sp[i].company);
printf("%d\n", i, sp[i].cylinder);
printf("%d\n", i, sp[i].year);
printf("%d\n", i, sp[i].plates);
}
if (sp) {
free(sp);
}
getchar();
return 0;
}
void function(int maxcars) {
//
int i;
for (i = 1; i < maxcars; i++) {
sp = malloc(maxcars * sizeof(struct car));
printf("Struct for car no%d is beeing created\n", i);
printf("Give Name: \n");
scanf("%s",sp[i].name);
printf("Give Manufactorer Company: \n");
scanf("%s",sp[i].company);
printf("Give Cylinder Capacity: \n");
scanf("%d",sp[i].cylinder);
printf("Give Year of Production: \n");
scanf("%d",sp[i].year);
printf("Give Plate Number: \n");
scanf("%d",sp[i].plates);
printf("%s\n",sp[i].name);
printf("%s\n",sp[i].company);
printf("%d\n",sp[i].cylinder);
printf("%d\n",sp[i].year);
printf("%d\n",sp[i].plates);
}
}
//编辑:稍后修复了一些功能后,我有一些错别字但不会影响我的主要问题..崩溃仍在发生
//编辑2-解决方案:最终是&amp;在scanf中丢失了...谢谢指出dave!我感觉这是显而易见的事情。