简体   繁体   中英

Setting value of string in function does not work

void func(char *var) 
{
    var = "Hello"; 
}

int main () {
   char var[10];
   func(var);
   printf ("var is %s", var);
}

Why doesn't the above code work in C? (printf displays nothing). Changing var = "hello;" to strcpy(var, "hello"); fixes it:

void func (char *var) 
{
    strcpy(var, "HELLO");
}

Because var = "Hello" modifies the argument var . Arguments are stored in new variables - this doesn't modify the value of the other variable (also called var ) in main .

In other words, it doesn't work for the same reason this doesn't work:

void func(int i)
{
    i = 7;
}

int main()
{
    int i = 0;
    func(i);
    printf ("var is %i", var);
}

Now, consider these two functions (and a global variable):

int five = 5;

void func1(int *p)
{
    p = &five;
}

void func2(int *p)
{
    *p = five;
}

int main()
{
    int i = 0;
    printf("%d\n", i); // prints 0 (duh)
    func1(&i);
    printf("%d\n", i); // still prints 0
    func2(&i);
    printf("%d\n", i); // prints 5
}

Do you know the difference? func1 modifies p itself (by setting it to the address of five ). p is a local variable in func1 , so there's no reason that changing it would affect anything in main .

On the other hand, func2 modifies the thing p points to . And p points to the local variable i in main - so this one does modify i in main !

Now consider these functions:

void func3(char *s)
{
    s = "Hello";
}
void func4(char *s)
{
    strcpy(s, "Hello");
}

The string literal ( "Hello" ) is a red herring here, so let's mostly remove it from the equation:

char hello_string[] = {'H', 'e', 'l', 'l', 'o', '\0'};
char *hello_string_pointer = &hello_string[0];

void func3(char *s)
{
    s = hello_string_pointer;
}
void func4(char *s)
{
    strcpy(s, hello_string_pointer);
}

func3 couldn't possibly affect anything in main , for the same reason that func1 can't - s is a local variable inside func3 , and we're only changing s .

On the other hand, func4 calls strcpy . Do you know what strcpy does? It does the equivalent of this:

void func4(char *s)
{
    for(int k = 0; k < 6; k++)
        *(s + k) = *(hello_string_pointer + k);
}

Some pointer arithmetic there, but the point is, it modifies *the thing s points to , and the 5 things after it - which are the first 6 elements of the array in main`.

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