typedef struct roads road;
typedef struct city city;
I am implementing a code that has a road, two cities on its edges, I will read them from a file and make them linked. Structure is like
NewYork 250km LosAngeles
LosAngeles 120km Florida
and such, I will be having a ROADS array that stores the roads that I've read.
struct city{
char* city_name;
}
struct roads{
int distance;
struct city *next_city,*previous_city;
struct roads **neigbors; // is this possible
}
size_t size = sizeof(road) + sizeof(city);
road *ROADS = malloc(size);
what would be the shortcomings of such a code and the allocation for this, I am thinking of doing a map for a country. All cities should have a pointer to its neighbors so that when someone asks what is the distance between them, my program should be able to answer it.
char *city_name = malloc(sizeof(char)*length_of_name);
road *given_road = malloc(sizeof(road));
city *given_city = malloc(sizeof(city));
when it comes to neighbors part;
for(index = 0; given_road[index] != NULL; index++)
road *given_road->neighbors[index] = malloc(sizeof(city));
this part and the last part are the parts that I got confused, my only linking reference is the names of the cities;
if(strcmp(ROADS[i]->next_city->city_name,ROADS[j]->previous_city->city_name)){
if(ROADS[i]->neighbors[0]==NULL)
ROADS[i]->next_city = ROADS[j]->previous_city;
ROADS[i]->neighbors[0] = ROADS[j]->previous_city;
ROADS[j]->neighbors[0] = ROADS[i]->next_city; //I totally don't know what am I doing here}
I intended that if the the road in ROADS[i]'s city_name is the same with ROADS[j]'s city_name (like LosAngeles example), I'll try to make them connected via neighbors structure, so that "NewYork 250km LosAngeles" road has one neighbor which is "LosAngeles 120km Florida", and vice versa. If something like "LosAngeles 500km Nebraska" is read from file, then two of my first mentioned roads will have two neighbors and two links as well. ROADS array then now storing 3 road structures. Of course I am allocating memory for ROADS array when I make road structures.Everytime a road comes;
ROADS = realloc(ROADS,i*size + size);
Where are the points that I do wrong? Any hint would be perfect for me to develop this code further, even saying the "concept that I should search" in order to do what's on my mind would be great.
To address the title of your post storing a pointer in a struct referencing the same type of struct is completely valid and used all the time in linked lists, which is a very similar use-case to yours - e.g. anytime you need to link together similar structs.
Have a look at this page.
I see you have an extra level of pointing going on you can can have an array of pointers to structs. Looks like a reasonable approach to me.