I've been struggling to make a dynamically changing array of structures in C. My array size should change depending on how many times user decides to write data (city1 city2 and distance). I'm talking about addEdge function, which is supposed to make a bigger array every time user inputs data; it's also supposed to store structures in this array. I've used realloc function but it doesn't seem to work. In my main function I ask user to write his data twice and start my function after every input. It, for some reason, works after first function initialization, but it crashes after the second time. My intention is that it worked in a loop (user adds as much data as he wants). Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct edge{
char city1[30];
char city2[30];
int distance;
}edge;
void addEdge(edge **tab, char* city1, char* city2, int distance, int* n);
int main()
{
edge *tab;
tab=(edge*)malloc(0);
char city1[30], city2[30];
int distance, n=1;
printf("\nType cities and distance in form: 'city1 city2 distance'\n");
scanf("%s %s %d", city1, city2, &distance);
addEdge(&tab, city1, city2, distance, &n);
printf("\nType cities and distance in form: 'city1 city2 distance'\n");
scanf("%s %s %d", city1, city2, &distance);
addEdge(&tab, city1, city2, distance, &n);
system("pause");
return 0;
}
void addEdge(edge **tab, char* city1, char* city2, int distance, int* n)
{
edge edgeN;
strcpy(edgeN.city1, city1);
strcpy(edgeN.city2, city2);
edgeN.distance=distance;
*tab=(edge*)realloc(*tab, *n * sizeof(edge));
*tab[*n-1]=edgeN;
*n=*n+1;
}
malloc(0)to do?malloc(0)is in a way important, becauserealloc()needs to get a pointer previously returned bymalloc(). Fromrealloc's man page: * Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc(), or realloc()*scanf(), so you don't know if there's garbage in yourcity1andcity2arrays.