Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 780
AisIceEyes Avatar asked Dec 07 '22 08:12

AisIceEyes


1 Answers

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;
}
like image 110
Ed S. Avatar answered Dec 28 '22 23:12

Ed S.