Correctly pass a char array and char pointer to function by reference in C

61,096

There is no such thing as pass by reference in C. Everything in C is passed by value. This leads to the solution you need; add another level of indirection.

However, your code has other problems. You don't need to pass a pointer to pointer (or pointer to array) because you are not mutating the input, only what it refers to. You want to copy a string. Great. All you need for that is a pointer to char initialized to point to a sufficient amount of memory.

In the future, if you need to mutate the input (i.e., assign a new value to it), then use a pointer to pointer.

int mutate(char **input) 
{
    assert(input);
    *input = malloc(some_size);
}

int main(void)
{
    /* p is an uninitialized pointer */
    char *p;
    mutate(&p);
    /* p now points to a valid chunk of memory */
    free(p);
    return 0;
}
Share:
61,096
AisIceEyes
Author by

AisIceEyes

Updated on July 09, 2022

Comments

  • AisIceEyes
    AisIceEyes almost 2 years

    Is there a right way to call a char array and a char pointer to go to a function but it's pass by reference where it will also be manipulated?

    Something like this:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void manipulateStrings(char *string1, char *string2[])
    {
    
        strcpy (string1, "Apple");
        strcpy (string2, "Banana");
    
        printf ("2 string1: %s", string1);
        printf ("2 string2: %s", &string2);
    
    }
    
    
    int main ()
    {
        char *stringA;
        char stringB[1024];
    
        stringA = (char *) malloc ( 1024 + 1 );
    
        strcpy (stringA, "Alpha");
        strcpy (stringB, "Bravo");
        printf ("1 stringA: %s", stringA);
        printf ("1 stringB: %s", stringB);
    
        manipulateStrings(stringA, stringB);
    
        printf ("3 stringA: %s", stringA);
        printf ("3 stringB: %s", stringB);
    
    
        return 0;
    }
    

    I am not sure if I'm understanding correctly how to pass such variables to a function and change the values of those variables who happen to be char / strings

    Edit: My question is - How would you be able to change the values of the two strings in the function?