Search code examples
cpointersdynamic-memory-allocationpass-by-value

Modifying a pointer in a function


I've made a function that allows the input of a string via keyboard. This function has two arguments: the maximum possible length of the string and a pointer to char. What happens inside the function is that an array of characters, which has as many elements as the maximum length, gets declared and then the string given by the user gets temporarly stored in that very array. Once the acquisition of the string is done, I use the calloc function to allocate just the right amount of memory to store that same string in the pointer to char that has been passed as an argument.

int main(void)
{
    char* test;

    stringInput(test, 10);

    printf("%s", test);

    return 0;
}

void stringInput(char* string, int maxStringLength)
{
    char tempString[maxStringLength];

        //STRING GETS PROPERLY STORED IN tempString

    string = (char*)calloc(strlen(tempString)+ 1, sizeof(char));

    strcpy(string, tempString);

    return;
}

This sorts of work, meaning that if I try to print "string" before this function hits return, the program actually displays what it is supposed to. However, when I try to print "test" in the main function, it doesn't print anything, which means that stringInput isn't modifying the pointer that gets passed to it. I've further confirmed this by printing the address of "test" before the function call, after the calloc line and again after the function call, which showed me that it changes after the calloc but then gets back to its previous value when the function ends. How can I solve this problem?


Solution

  • The problem here is, test itself is passed by value, which is stored in string, and any change you make to string will not reflect back to test.

    You need to pass a pointer to test, if you want to modify test itself.

    Something like

     stringInput(&test, 10);
    

    and

    void stringInput(char** string, int maxStringLength)
    {
        char tempString[maxStringLength];
    
            //STRING GETS PROPERLY STORED IN tempString
    
        *string = calloc(strlen(tempString)+ 1, sizeof(char));  // no need to cast
        if (!string) {
           printf("error in calloc!!\n");
           return;
         }
        strcpy(*string, tempString);
    
        return;
    }