c - 为什么从 n 格式说明符获取值时需要使用 & 符号?

标签 c syntax

为什么从 n 格式说明符获取值时需要使用 & 符号?

例如:

...
int n;
printf("%s: %nFoo\n", "hello", &n);

%npointer 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/

相关文章:

java - 修改Java语法

c - 如何使用putchar打印浮点值?

c - 理解链表语法

c# - 什么是隐式泛型类型参数

Windows 命令行 |此批处理行的正确 qoutes/语法是什么

CSS 字体系列 : Use Apostrophe quotes or Quotation marks to surround names with spaces?

c - 获取: 'cast to pointer from integer of different size' warning (amd64)

c - 数组指针与普通指针的区别

c - WebAssembly:(f32.const nan:0x200000) 表示 0x7fa00000 或 0x7fe00000

c - 陷阱处理程序、异常处理程序和中断处理程序与系统调用有何不同?