How do I change the actual argument passed to a function in C?

I want to change the actual argument passed to the function, not a copy of it. For example:

char str[] = "This is a string";

      

I want to create a function after the call for which the value str

is different. I tried to create a function that takes char**

as an argument, but I just couldn't get what I want.

-1


source to share


4 answers


I think you mean something like this:

void update_string(char ** ptr)
{
    *ptr = strdup("This is a test");
    return;
}

      



Then call the function like this:

char * str = strdup("hello world\n");
printf("%s\n", str);
update_string(&str);
printf("%s\n", str);

      

+2


source


You can go through char*

. The pointer will be copied, but it will still point to the same line



If you need to pass the pointer itself (and not a copy of it), you must pass char**

0


source


To modify a string passed to a function in place, use a regular pointer. For example:

void lower_first_char(char *str)
{
    *str = tolower(*str);
}

      

After executing this function, the first character of the passed string will be changed to lowercase.

0


source


Pass char*

in if you want to change the actual line:

foo(str);
...
void foo(char *some_string) {
   some_string[0] = 'A';
}

      

str

now hold "Ahis is a string"


If instead of str

being an array, you had: char *str = "Hello";

and wanted to change where you str

pointed out, then you must pass char**

:

bar(&str);
...
void bar(char **ptr_string) {
   *ptr_string = "Bye";
}

      

str

now points to "Bye"

.

0


source







All Articles