簡體   English   中英

函數中字符串的設置值不起作用

[英]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);
}

為什么上面的代碼在 C 中不起作用? ( printf 不顯示任何內容)。 改變var = "hello;" strcpy(var, "hello"); 修復它:

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

因為var = "Hello"修改了參數var 參數存儲在新變量中 - 這不會修改main另一個變量(也稱為var )的值。

換句話說,它不起作用的原因與不起作用的原因相同:

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

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

現在,考慮這兩個函數(和一個全局變量):

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
}

你知道這有什么區別嗎? func1修改p本身(通過將其設置為five的地址)。 pfunc1的局部變量,所以沒有理由改變它會影響main任何內容。

另一方面, func2修改p指向的東西 並且p指向main的局部變量i - 所以這個變量確實修改了main i

現在考慮這些函數:

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

字符串字面量 ( "Hello" ) 在這里是一個紅鯡魚,所以讓我們主要從等式中刪除它:

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不可能影響main任何內容,原因與func1不能 - sfunc3的局部變量相同,我們只更改s

另一方面, func4調用strcpy 你知道strcpy是做什么的嗎? 它的作用相當於:

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

那里有一些指針算術,但重點是,它修改了 * s指向的東西, and the 5 things after it - which are the first 6 elements of the array in main` 中, and the 5 things after it - which are the first 6 elements of the array in

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM