OiO.lk Blog C# Does malloc assign memory in the same location if you use the same variable name again on every iteration of a loop?
C#

Does malloc assign memory in the same location if you use the same variable name again on every iteration of a loop?


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 a 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.



You need to sign in to view this answers

Exit mobile version