c - 带有隐式空字符的 sizeof() 和 strlen()

标签 c arrays string sizeof

如果我是对的,在数组c 中,\045 被视为单八进制,其对应的ASCII 字符是%。因此 sizeof(c) 是 4。

同样在数组d中,\099应该被当作单八进制值,对应的ASCII字符是R sizeof(d) 应该是 4,但不是。

您能否详细说明 sizeof(d)sizeof(e) 的情况?

代码:

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

int main(void)
{
    char      a[] = {"12345"};
    char      b[] = {"12345\0"};

    char      c[] = {"12\045"};
    char      d[] = {"12\099"};
    char      e[] = {"12\0133"};

    printf("\ta         = %s  \n", a);
    printf("\tsizeof(a) = %ld \n", sizeof(a));
    printf("\tstrlen(a) = %ld \n", strlen(a));

    printf("\n");

    printf("\tb         = %s  \n", b);
    printf("\tsizeof(b) = %ld \n", sizeof(b));
    printf("\tstrlen(a) = %ld \n", strlen(b));

    printf("\n");
    printf("\tc         = %s  \n", c);
    printf("\tsizeof(c) = %ld \n", sizeof(c));
    printf("\tstrlen(c) = %ld \n", strlen(c));

    printf("\n");

    printf("\td         = %s  \n", d);
    printf("\tsizeof(d) = %ld \n", sizeof(d));
    printf("\tstrlen(d) = %ld \n", strlen(d));

    printf("\n");

    printf("\te         = %s  \n", e);
    printf("\tsizeof(e) = %ld \n", sizeof(e));
    printf("\tstrlen(e) = %ld \n", strlen(e));

    return (0);
}

实际结果:

    a         = 12345  
    sizeof(a) = 6 
    strlen(a) = 5 

    b         = 12345  
    sizeof(b) = 7 
    strlen(a) = 5 

    c         = 12%  
    sizeof(c) = 4 
    strlen(c) = 3 

    d         = 12  
    sizeof(d) = 6 
    strlen(d) = 2 

    e         = 12
                      3  
    sizeof(e) = 5 
    strlen(e) = 4

最佳答案

'9' 不是有效的八进制数字。字符串 "\099" 是一个 '\0' 后跟两个 '9' 字符。因此,字符串长度为 2,数组长度为 6。'\0' 是字符串终止符。

d[] 的初始化等价于:

char e[] = { '1','2','\0','9','9','\0' } ;

关于c - 带有隐式空字符的 sizeof() 和 strlen(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57677572/

相关文章:

字符指针在附加字符串字符时添加随机值

Python:如何将两个平面列表组合成一个二维数组?

java - 字母数字拨号盘搜索 - Java/Android

javascript - 正则表达式拆分并记住匹配(优雅)

python - 在 Python 中使用通配符匹配字符串

c - 初始化变量时程序停止响应

c++ - 如何自动将枚举转换为字符串

string - 流字符串值的近似直方图(卡片目录算法?)

c - 如何编辑我的代码以便输出用户输入的两个特定字符的频率? (C语言)

arrays - 当 UIPanGesture 上的状态为 .ending 时循环遍历数组