I am writing code to take in a weighted adjacency list in C. Each edge is stored in the form of a struct. I created an array of pointers where each pointer leads to the list for a node. Here's what I did:
#include <stdio.h>
#include <stdlib.h>
struct edge {
int u;
int v;
int w;
};
// taking a weighted adjacency list
int main() {
int n; // number of nodes
scanf("%d ", &n);
struct edge **list[n];
int p = n;
while (p) {
struct edge *n_list = (struct edge *)malloc(n * sizeof(struct edge));
int num = 1;
for (int i = 0; i < n; i++) {
n_list[i].u = n - p;
scanf("%d ", &n_list[i].v);
if (n_list[i].v == -1) {
n_list[i].w = -1;
break;
} else {
num++;
scanf("%d ", &n_list[i].w);
}
}
n_list = (struct edge *)realloc(n_list, num * sizeof(struct edge));
list[n - p] = &n_list;
struct edge *ptr = *list[n - p];
for (int j = 0; j < num - 1; j++) {
printf("%d %d %d\n", ptr[j].u, ptr[j].v, ptr[j].w);
}
p--;
}
}
The problem is that the edges get printed correctly but after the whole iteration over p (number of nodes), every element in the array of pointers (list) has the same address stored. I'm guessing that everytime I use malloc for n_list, it is allocating memory in the same location, thereby erasing the list for the previous node when I start taking input. How can I ensure this does not happen? Also any easier methods to go about this task are welcome.
list[n-p]=&n_list;what is&n_list?WIll it ever change between nodes? You must allocate memory forlist[x], not only forlist. BTW:mallocdoes not know what you do with the result. Your assumption to return same address is wrong.&n_list.n_listis a local variable which only exists once. If you take the address of it, it will always be the same. That means, in each iteration of overwrite previous content and alllist[x]entries will point to the same address. Additionally, that address will become invalid as soon as you leave thewhile(p)loop.struct edge* list[n];malloccall,malloc(n*sizeof(struct edge)). Do you see the namen_listanywhere in there? It is not. Sincemallocis not passed the name that its return value will be assigned to, there is no way it could make any decision based on the name.