Passing a double pointer to change a string

So, I have a program that works sometimes, but sometimes it doesn't. Sometimes including a printf statement will do the magic job of the program (and sometimes printf will make it break). This makes me think I got it confused until the pointers / selections disappeared as I still have problems wrapping my head around some things. The program is too long to post all the code, so I'll just show you where I think the problem is.

I was provided with a function that takes FILE * and multiple char ** as parameters, returning an int. The function parses the file, keeping the required lines pointed to by the double pointers.

This is how I used the function (a lot of code omitted / simplified):

char **s1;
char **s2;
char **s3;

int main(int argc, char ** argv){
    s1 = (char**)malloc(20);
    s2 = (char**)malloc(20);
    s3 = (char**)malloc(20);

    /* Unnecessary code omitted */
    read(inFile);
}

int read(FILE* in){
    /* omitted code */
    parse(in,s1,s2,s3);
    printf("%s",*s1); /* This is to show how I access the strings */
}

      

I'm pretty sure that somewhere in my program these lines are being overwritten because I was not allocating memory correctly. Hopefully my error is visible in the code snippet I gave because I don't have many other theories as to why my code is not working.

+3


source to share


1 answer


Since the API before parse()

is specified with char **

, I believe it's safe to assume that you really need double feedback in the call, but not in the declaration.

So, you probably need to skip the calls malloc()

and say:



char *s1, *s2, *s3;
...
parse(in, &s1, &s2, &s3);

      

This would allow it to parse()

allocate its own space and return three pointers to its caller, changing the pointers themselves. I appreciate your efforts to strip the question down to its core, but it would be interesting to see a prototype for parse ().

+2


source







All Articles