1

I have a problem while passing a ptr to the function loadSignatures. at the end of loadSignatures function the virusList has the address I wish, but then it returns to the main with unexpected address.

void loadSignatures(char* fileName, link* virusList){
    FILE* f = fopen(fileName, "rb");
    virus* v = readVirus(f);
    while (v){
        virusList = list_append(virusList,v);
        v = readVirus(f);
    }
    fclose(f);
}

int main(int argc, char **argv) {
    link *virusList = NULL;
    char fileName[30];
    gets(fileName);
    loadSignatures(fileName, virusList);
    list_print(virusList, stdout);
    list_free(virusList);
}

even when I try to do this:

link* loadSignatures(char* fileName, link* virusList){
    FILE* f = fopen(fileName, "rb");
    virus* v = readVirus(f);
    while (v){
        virusList = list_append(virusList,v);
        v = readVirus(f);
    }
    fclose(f);
    return virusList;
}

int main(int argc, char **argv) {
    link *virusList = NULL;
    char fileName[30];
    gets(fileName);
    virusList = loadSignatures(fileName, virusList);
    list_print(virusList, stdout);
    list_free(virusList);
}

It doesn't work properly.

I will be glad to know the right way to deal with this issue.

  • The first version is clearly wrong because `virusList` is a **local** variable inside `loadSignatures` so any changes to it does not change the variable in `main`. The second fixes that. So can you describe in more detail what "doesn't work" means? Also, please provide a [minimal verifiable example](https://stackoverflow.com/help/minimal-reproducible-example) as code like `list_append` and `list_print` are missing so we can't check whether that is doing anything wrong. – kaylum Apr 12 '20 at 11:36

1 Answers1

1

This line changes a local copy of virusList:

virusList = list_append(virusList,v);

To change virusList, you need to pass the address of virusList. As in:

void loadSignatures(char* fileName, link** virusList){
    FILE* f = fopen(fileName, "rb");
    virus* v = readVirus(f);
    while (v){
        *virusList = list_append(*virusList,v);
        v = readVirus(f);
    }
    fclose(f);
}

and to call it:

loadSignatures(fileName, &virusList);
Shlomi Agiv
  • 1,183
  • 7
  • 17