Search code examples
cpass-by-reference

How do I pass a pointer to a local variable?


I am having some trouble passing pointers to local variables. When I try printing the printf statement in main(), I get random numbers each time. But when I print it from the parse function, it works fine. I have tried playing around with the pointers and cannot figure it out.

#include <stdio.h>
#include <stdlib.h>


void parse(char record[], int *acct, float *amnt){
            char word1[10], word2[10];
            sscanf(record, "%s %s", word1, word2);

            acct = (int*) malloc(10);
            amnt = (float*) malloc(10);

            *acct = atoi(word1);
            *amnt = atof(word2);

            printf("%d, %.1f\n", *acct, *amnt);
}

int main(){
            FILE *p = fopen("accounts.ssv", "rt");
            char record[20];
            int acct;
            float amnt;

            while (fgets(record, 20, p)){
                    parse(record, &acct, &amnt);
                    printf("%d, %.1f\n", acct, amnt);
            }

            fclose(p);
            return 0;
}

accounts.ssv

20 -50.5
10 60.5
20 30.0

Solution

  • You are passing pointers to main()'s acct and amnt, but the malloc calls are replacing those pointers with pointers to newly allocated memory.

    These lines:

       *acct = atoi(word1);
       *amnt = atof(word2);
    

    write to the newly allocated memory instead of the variables in main().

    Try removing the two malloc calls, and the atoi/atof functions will store their result in the main() variables.