[英]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?为什么上面的代码在 C 中不起作用? (printf displays nothing). ( printf 不显示任何内容)。 Changing var = "hello;"
改变var = "hello;"
to strcpy(var, "hello");
到strcpy(var, "hello");
fixes it:修复它:
void func (char *var)
{
strcpy(var, "HELLO");
}
Because var = "Hello"
modifies the argument var
.因为var = "Hello"
修改了参数var
。 Arguments are stored in new variables - this doesn't modify the value of the other variable (also called var
) in main
.参数存储在新变量中 - 这不会修改main
另一个变量(也称为var
)的值。
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
). func1
修改p
本身(通过将其设置为five
的地址)。 p
is a local variable in func1
, so there's no reason that changing it would affect anything in main
. p
是func1
的局部变量,所以没有理由改变它会影响main
任何内容。
On the other hand, func2
modifies the thing p
points to .另一方面, func2
修改p
指向的东西。 And p
points to the local variable i
in main
- so this one does modify i
in main
!并且p
指向main
的局部变量i
- 所以这个变量确实修改了main
i
!
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:字符串字面量 ( "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
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
. func3
不可能影响main
任何内容,原因与func1
不能 - s
是func3
的局部变量相同,我们只更改s
。
On the other hand, func4
calls strcpy
.另一方面, func4
调用strcpy
。 Do you know what strcpy
does?你知道strcpy
是做什么的吗? 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`.那里有一些指针算术,但重点是,它修改了 * 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.