chararray的大小和长度是不一样的

Mat*_*ger 0 c arrays

我已经有了几年的Python,C#和Java经验,我刚开始学习C语言.

我在教程中学到了,这char anything[]总是一个指针.(今天有人告诉我这是错的) - 我认为我的问题与此有关.不过,我正在尝试获取char数组的长度:

#include <stdio.h>

int get_string_length(char * string)
{
    int length = 0;
    while(string[length] != '\0')
    {   
        char c = string[length];
        length++;
    }
    return length;
}

int get_string_size(char * string)
{
    return sizeof(string);
}

int main()
{
    printf("%d\n", get_string_size("hello world")); // returns 8
    printf("%d\n", get_string_length("hello world")); // returns 11
    printf("%d\n", sizeof("hello world")); // returns 12 -> Okay, because of '\0'-char
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

8

11

12

那么,为什么我的get_string_size方法会返回8而不是12?(因为两者都只打电话sizeof())

Bat*_*eba 5

char anything[]指针?不完全的.

文字 的实际类型"hello world"是a const char[12].(注意NUL终结符的额外元素).

但是当传递给函数时,这种类型会衰减到a const char*.

所以get_string_size返回sizeof(const char*)其是8平台(即,一个的sizeof上char*),但sizeof("hello world")sizeof(const char[12])这是12,由于sizeof (char)是由C标准定义为1.

get_string_length 从传递给它的指针开始返回第一个NUL终止符的位置.

最后,请注意您应该使用返回类型%zu的格式说明符sizeof:从技术上讲,行为printf("%d\n", sizeof("hello world"));未定义的.