无法在C中正确获取数组的大小

标签 c arrays sizeof

我正在做的练习要求创建一个 50 个字符的数组,将其放入一个结构中,然后使用子例程在屏幕上打印该数组并说出它有多少个字符(还有更多,但问题是我的就在这里)

这就是我所做的

    #include <stdio.h>
    #include <string.h>

    int Anzahl (char []);

    int main ()

    {
    int x;
    char kette [50];
    printf ("Type down something\n");
    fgets (kette,50,stdin);

    struct hullo {
        char kette [50];
    };
    x=Anzahl (&kette[50]);
    printf ("the number of letters is : %d", x);
    }


    int Anzahl (char kette[50])
    {
    int x1;
    puts (&kette[50]);
    x1 = sizeof (kette[50]);
    return x1;
    }

`

但是每次我输入一些东西,最后字符数总是1。 如果有人能向我解释我做错了什么,那就太好了。

最佳答案

你在两个方面都错了。

首先,函数调用

 x=Anzahl (&kette[50]);

是错误的(不是语法上的,从实际使用来看),需要传递星号地址,就像x=Anzahl (kette);

其次,数组作为函数参数传递时,会延迟指向第一个元素的指针。因此,您无法使用 sizeof 从接收输入参数的参数中获取预期的 size

引用 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.

以及第 §6.7.6.3 章

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. [...]

奖金:

  puts (&kette[50]);

也是错误的。它相差一,因为 C 数组是从 0 开始索引的。在这种情况下,您传递了一个无效指针(并访问其内存位置以读取内容),您有 undefined behavior .

关于无法在C中正确获取数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47813866/

相关文章:

python - 根据存储在另一个数组或列表中的索引拆分 numpy 多维数组

javascript - 在 json、node.js 中查找对象的值

在函数内部使用时 c 数组大小的变化

c++ - 获取对象 void* 指向的大小

c - 为什么我在使用 malloc 并使用 sizeof 打印后没有得到正确的大小?

c++ - 在 c/c++ 中分配指针

arrays - 在 Swift 3 中加载数据时为空数组

c - C函数中任意数组类型的长度

python - 需要从 Python 将指针传递给 C 共享库函数

c - 如何更改C语言程序的默认图标?