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

标签 c arrays pointers scanf

为什么我必须在 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/

相关文章:

c - 是否可以在 TCP 3 次握手中获取 SYN/ACK 数据包的 TCP 序列号?

c - 如何覆盖不直观的代码块?

c - 二维数组中间的内存地址越界?

php - jqplot - 使用 php 数组中的值

pointers - Fortran 指针虚拟参数

复制后访问对象时 C++ 程序崩溃

c++ - 将 'this' 指针传递给 SetWindowsHookEx 的 MouseProc

java - 如何在鼠标事件发生后从数组列表中删除对象?

c++ - 将文件中的数据读取到类的数组中

c++ - C 字符串和字符数组声明