为什么从 n 格式说明符获取值时需要使用 & 符号?
例如:
...
int n;
printf("%s: %nFoo\n", "hello", &n);
%n
是 pointer to an integer type
而&符号是一个地址,那么为什么它会将上例中格式说明符的结果转换为整数呢?
最佳答案
%n
说明符给出了到目前为止打印的字符数,因此它是一个输出值,您添加运算符的 &
地址,将地址传递给n
的值,因此可以在 printf()
内部修改它,并且当 printf()
返回时,它已存储 n 中的字符数code>n
变量,通过使用指向它的指针。
如何修改函数中的值的示例如下
void setValue(int *where, int howMuch)
{
if (where == NULL)
return;
*where = howMuch;
}
int main()
{
int value;
setValue(&value, 8);
/* ^ here is where the & address of is important */
printf("%d\n", value);
return 0;
}
输出将是
8
请注意,在 c 中,没有通过引用传递
,因此修改函数中变量的唯一方法是传递它的地址并从函数访问指针。
关于c - 为什么从 n 格式说明符获取值时需要使用 & 符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651054/