C函数参数可以设置变量吗?
我不知道在下面的C代码中如何设置firstname和lastname变量C函数参数可以设置变量吗?,c,function,parameters,C,Function,Parameters,我不知道在下面的C代码中如何设置firstname和lastname变量 printf("Hello, %s, %s\n", firstname, lastname); 看起来readln函数的char[s]参数正在设置firstname和lastname 这是可能的,如果是的话,这叫什么,这样我可以做一些研究 谢谢 编辑:下面是一个更简单的版本。看起来该参数正在设置一个变量 int foo(char s[]){ s[0]='w'; s[1]='\0'; return
printf("Hello, %s, %s\n", firstname, lastname);
看起来readln函数的char[s]参数正在设置firstname和lastname
这是可能的,如果是的话,这叫什么,这样我可以做一些研究
谢谢
编辑:下面是一个更简单的版本。看起来该参数正在设置一个变量
int foo(char s[]){
s[0]='w';
s[1]='\0';
return 5;
}
int main() {
char name[2];
int wtf;
wtf = foo(name);
printf("%s\n", name);
}
参数char s[]是设置名称
将数组作为参数传递给函数时,与传递数组地址完全相同。然后,函数可以修改这个地址的上下文,也就是数组本身 例如,该函数可以定义为int readlnchar*s、int maxlen,并且该函数将保持不变 调用函数时,可以使用readlnfirstname、STRLEN或readln&firstname[0],STRLEN。这两个函数都可以使用任意一个函数定义,它们是正交的
这是一个很好的主题。一般术语是通过引用传递-readln中的形式参数s指的是实际参数firstname和lastname在各自的函数调用中所使用的内存块 C实际上按值传递所有函数参数-函数定义中的形式参数是内存中与函数调用中的实际参数不同的对象,实际参数的值复制到形式参数:
void swap( int a, int b ) // a receives a *copy* of x's value, b receives
{ // a *copy* of y's value
int t = a; // updates to a and b have no effect on x and y
a = b;
b = t;
}
void bar( void )
{
int x = 1, y = 2;
swap( x, y ); // x and y are not actually updated
}
我们通过传递指向要修改的对象的指针来伪造引用传递语义:
void swap( int *a, int *b ) // a receives the *address* of x, b receives the
{ // address of y
int t = *a; // updates to *a and *b *do* have and effect on
*a = *b; // x and y
*b = t;
}
void bar( void )
{
int x = 1, y = 2;
swap( &x, &y ); // instead of passing the *values* of x and y,
} // we pass their addresses.
同样,a和b在内存中是与x和y分开的对象,但它们不是接收x和y的值,而是接收它们的地址。瞧
数组的情况有点奇怪-除非是sizeof或一元&运算符的操作数或用于初始化声明中字符数组的字符串文字,否则N-element array of T类型的表达式将转换为指向T的指针类型的表达式,表达式的值将是数组中第一个元素的地址
因此,如果将数组表达式传递给函数,函数实际接收的是指向数组第一个元素的指针,因此不需要在函数调用中使用&运算符。这就是readln正在发生的事情;参数s指向函数调用中数组的第一个元素 通过参考传递?很有趣。非常感谢。澄清这种愚蠢的行为只适用于数组?是的,数组的行为有点混乱。如果传递原语或结构而不使用&它们将按值传递,这与数组不同。@seamus Re:仅适用于数组?当函数用作函数参数和其他情况时,函数也会转换为指向函数的指针:foorand。然而,接收函数fooint*f肯定不能通过该指针读取或写入函数rand。它可以执行该函数。@SHG这就像传递数组地址一样。->几乎这与传递数组第一个元素的地址完全相同。这种差异很微妙。这两个地址的值相等,但类型不同,很少有位模式。
void swap( int *a, int *b ) // a receives the *address* of x, b receives the
{ // address of y
int t = *a; // updates to *a and *b *do* have and effect on
*a = *b; // x and y
*b = t;
}
void bar( void )
{
int x = 1, y = 2;
swap( &x, &y ); // instead of passing the *values* of x and y,
} // we pass their addresses.
a == &x;
b == &y;
*a == x;
*b == y;