Why does this crash? It gets up to asking for the name in the getstruct func, then just crashes, compiles fine but crashes afterwards. Also is there a better way to get an integer instead of having to take 48 away from what I get as a character to get its numeric value? (Without using scanf).
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct tnode {
char *name;
int age;
char *postcode;
} person;
void getstruct(void);
int main()
{
int i, j;
i = 0;
printf("Hello, please number of people: ");
i = getchar();
i = i - 48;
for(; j<i; j++)
{
getstruct();
}
return 0;
}
void getstruct(void)
{
FILE *fp;
person rec;
int i;
i = 0;
printf("\nEnter name: ");
while((rec.name[i++] = getchar()) != '\n'){}
rec.name[--i] = '\0';
printf("\nEnter age: ");
while((rec.age = (int)getchar()) != '\n'){}
i = 0;
printf("\nEnter postcode: ");
while((rec.postcode[i++] = getchar()) != '\n'){}
rec.name[--i] = '\0';
printf("\nThank you.");
fp = fopen("data.txt", "w");
fprintf(fp, "%s %d %s\n", rec.name, rec.age, rec.postcode);
fclose(fp);
printf("\nInformation has been written to file!");
}
Any easier ways to do this? I tried using pointers and malloc and stuff but that got too complicated and I gave up and made the getstruct function take and return void.