【问题标题】:Why the function strlen() returns different values for the same length of two char arrays?为什么函数 strlen() 会为两个相同长度的 char 数组返回不同的值?
【发布时间】:2020-05-22 02:30:26
【问题描述】:
#include <stdio.h>
#include<string.h>

int main() {
    
    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

输出是

a的大小是50, B的大小是54

但我期望的是 a 的大小是 50 B的大小是50

这里有什么问题?

【问题讨论】:

  • ab 不是 字符串,因为它们都缺少 strlen() 要求的 null 字符
  • 我也想到巧合,试了好几次。
  • @isrnick - 我同意这是未定义的行为。
  • 大小为N 的数组最多可以存储一个包含N-1 非空字符加上表示字符串结束的空字符的字符串。因此,由于您的数组大小为 50,因此您的 for 循环应该上升到 j&lt;49,并且在循环之后应该将空字符分配到两个数组 b[49]='\0'; a[49]='\0'; 中的第 49 位。

标签: c arrays strlen


【解决方案1】:

这里有什么问题?

问题是你没有终止你的字符串。

C 要求字符串为null terminated:

通过搜索(第一个)NUL 字节来找到 C 字符串的长度。这可能很慢,因为相对于字符串长度需要 O(n)(线性时间)。这也意味着字符串不能包含 NUL 字符(内存中有 NUL,但它在最后一个字符之后,而不是在字符串中)。

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

int main() {

    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    // Terminate strings
    a[49] = b[49] = 0;

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

给出正确的结果。

【讨论】:

  • 请注意,您在循环内两个数组的索引 49 的位置写入字符 'b' 和 'a',然后在退出循环后用空字符覆盖它。
  • 应该是a[49]=b[49]='\0';你错误地输入了 a[49]=b[49]=0;
  • @FRANCISCASIMIRS '\0'0 是一样的。
  • @isrnick 是的,这是故意的。
猜你喜欢
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
相关资源
最近更新 更多