简体   繁体   中英

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

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

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

I want to create a function after a call to which the value of str is different. I tried to create a function accepting char** as the argument but I just couldn't get what I want.

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);

You may pass char* . The pointer will be copied, but it will still point to the same string

If you need the pointer itself to be passed (not its copy) you should pass a char**

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

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

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

Pass a char* if you want to modify the actual string:

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

str will now hold "Ahis is a string"


If instead of str being an array, you had: char *str = "Hello"; , and wanted to modify where str pointed , then you would pass a char** :

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

str will now point to "Bye" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM