tags:

views:

35

answers:

2

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!

A: 

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.

R..
+3  A: 

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!

Ignacio Vazquez-Abrams
Do I need to do it successively down the calling functions? Like char*** and then **suffix?
Daniel
Ignacio Vazquez-Abrams
and when I'm passing from the intermediate calling function, should I pass *suffix or just suffix?
Daniel
Any function that needs to change the value has to use a pointer pointer. If the function just reads the value then a pointer is fine.
Ignacio Vazquez-Abrams
Wait figured it out. Thanks!!!
Daniel
Thanks for replying so fast. Power to you :)
Daniel