This one will work:
//includes were missing
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR 100000
typedef struct city{
float x;
float y;
char *name;
}City;
City *GetCities(int *N){
int i;
char c;
City *list, *city;
//N is already a pointer so using a '&*' is confusing and I'm unsure whether this is at all valid syntax
scanf("%d", N);
//allocate enough memory! multiplied by number of cities
list = malloc(sizeof(City) * (*N));
for (i=0; i < *N; i++) {
//use pointer arithmetic to get the current city from the allocated block
//this needs to be done only once, now you can go on and reuse it extensively
city = list + i;
city->name = malloc(STR * sizeof(char));
if (city->name==NULL){
printf("Could not find enough memory");
}
while((c = getchar()) !='
' && c!= EOF);
//i hope rest is clear
fgets(city->name, STR, stdin);
//use city->name[strlen(city->name)-1]='' instead?
city->name[strcspn(city->name,"
")]='';
//at least you didn't forget the +1 in the realloc! :-)
city->name = realloc(city->name,(strlen(city->name)+1)*sizeof(char));
scanf("%f ", &city->x);
scanf("%f", &city->y);
}
return list;
}
//please also show the main, but I guess it was something like this
int main () {
int i, n;
City *cities, *city;
cities = GetCities(&n);
for (i=0; i < n; i++) {
city = cities + i;
printf("The %dth city "%s" got coordinates x=%f and y=%f!
", i, city->name, city->x, city->y);
//don't forget to free the name
free(city->name);
}
//don't forget to free the memory
free(cities);
}
I would also recommend to use a smaller line length buffer and run fgets in a loop to save ram space.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…