Daniel
Daniel

Reputation: 3

C: Passing a pointer down, updated pointer can't be accessed from calling functions!

I've got a problem- I assign my pointer variable to something in a called function, but when trying to access the updated pointer in the calling functions, it doesnt show as updated, and results in a seg fault. Help!

"Bottommost function":

void compareStrings(char* firstFrag, char* secondFrag, int* longestCommonLength, char* suffix, char* prefix, int* relative_pos) {
    suffix = firstFrag;
    prefix = secondFrag;
}

It is called from this function (the printf triggers the fault)

int findBestOverlap(char* fragmentArray[], int fragmentCount, int* longestCommonLength, char* suffix, char* prefix, int* relative_pos) {
    compareStrings(fragmentArray[firstFrag], fragmentArray[secondFrag], longestCommonLength, suffix, prefix, relative_pos);
    printf("LCL: %i || PREFIX: %s || SUFFIX: %s", *longestCommonLength, prefix, suffix);
}

The variables prefix and suffix are in turned created in a higher calling function, processStrings.

void processStrings(char* fragmentArray[], int fragmentCount) {
    int longestCommonLength = 0;
    char* suffix;
    char* prefix;
    int relative_pos;  // Where the first letter of suffix is, vis-a-vis prefix

    if ((findBestOverlap(fragmentArray, fragmentCount, &longestCommonLength, suffix, prefix, &relative_pos)) != 0) {
    }
}

Help!

Upvotes: 0

Views: 101

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

You're not updating the pointer, you're just changing the local value of the argument. You need to use a pointer pointer (e.g. char**) and change the pointed-to value instead.

void compareStrings(char* firstFrag, char* secondFrag, int* longestCommonLength, char** suffix, char** prefix, int* relative_pos) {
    *suffix = firstFrag;
    *prefix = secondFrag;
}

Then you need to dereference it appropriately in the caller. Have fun!

Upvotes: 3

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215261

If you need this functionality, you can either pass a pointer to the caller's copy of the pointer (so the called function can use that to write back to it) or you can simply return a pointer which the caller is expected to store and use.

Upvotes: 0

Related Questions