So I am trying to write this piece of code and test a few things out with structs.. It compiles but when I reach the "scanf("%d",sp[i].cylinder);" exe crashes when I give scanf an int input..Am I missing something obvious here?
#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);
}
}
//edit : fixed some later for after the function where i had a couple typos but wouldn't affect my main issue..crashing still happening
//edit 2- solution: It was eventually the & missing in scanf..thanks for pointing it out dave!i had a feeling it was something obvious..