gpt4 book ai didi

c - 将数组传递给 scanf 函数和变量

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:18 24 4
gpt4 key购买 nike

为什么我必须在 scanf("%type",&array[x]) 函数中传递类似数组的变量,而不是 scanf("%type",array[x]),我认为它们应该是指针“不能指向另一个地址的特殊指针”。如果我错了希望有人能澄清我。

另一件事在这里有两个简单的代码。哪一个更好 ?我对干净的编码很感兴趣,但是我还是初学者。

for(_a_i = 0; _a_i < _a_size; _a_i++) {

int _a_item;
scanf("%d", &_a_item);
_a[_a_i] = _a_item;

}

另一个

for(_a_i = 0; _a_i < _a_size; _a_i++) {

scanf("%d", &_a[_a_i]);

}

最佳答案

在特定情况下注意,只有类型为“array”的表达式会转换为“指向数组第一个元素的指针”。这不适用于单个数组元素,因此您必须在将值扫描到单个数组成员时显式使用 addressof 运算符。

也就是说,关于片段,

  • 两者都容易出错,因为您从未检查过 scanf() 的返回值以确保安全。
  • 所有以下划线开头的标识符都应该保留,不要在不必要的情况下尝试使用它们。

    引用 C11,章节 §7.1.3,保留标识符

    • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

注意:

引用 C11,章节 §6.3.2.1,(强调我的)

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

关于c - 将数组传递给 scanf 函数和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41678010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com