为什么当数组不包含空终止符时 strlen() 返回奇怪的结果? [英] Why does strlen() return strange result when array doesn't contain null terminator?

查看:37
本文介绍了为什么当数组不包含空终止符时 strlen() 返回奇怪的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个程序.两者都从字符串文字初始化数组.在一种情况下,数组大小正好是我想放入数组中的字符数.

I have two programs. Both initialize an array from a string literal. In one case the array size is exactly the number of characters I want to place in the array.

我想知道为什么 strlen() 返回的大小的输出对于两个程序来说都不同.是因为缺少终止空字符吗?如果是这样,那为什么输出是 16?

I wonder why the output of the size returned by strlen() differs for both prorgams. Is it because of the terminating null character is missing? If so, then why is the output 16?

#include<stdio.h>
#include<string.h>
main()
{
    char str[5] = "ankit";
    printf("size of = %d \n ",sizeof(str));
    int len = strlen(str);
    printf("length = %d \n ",len);
}

输出:- 大小 = 5,长度 = 16

#include<stdio.h>
#include<string.h>
main()
{
    char str[] = "ankit";
    printf("size of = %d \n ",sizeof(str));
    int len = strlen(str);
    printf("length = %d \n ",len);
}

输出:-大小= 6,长度= 5

推荐答案

在你的第一个代码中,通过编写

In your first code, by writing

 char str[5] = "ankit";

您没有任何空间可用于存储空终止符,而 str 必须在那里用作 string .因此,在这种情况下,strlen() 调用 未定义行为,通过超限分配的内存来寻找空终止符.

you don't have any space left for the null terminator to get stored, which is required to be there for str to be used as a string . So, in that case, strlen() invokes undefined behavior by overrunning the allocated memory in search of the null terminator.

OTOH,在第二个片段中,

OTOH, in the second snippet,

char str[] = "ankit";

您将大小分配留给编译器,它为用作初始值设定项的字符串文字中的元素以及空终止符分配内存.所以,你得到了想要的结果.

you leave the size allocation to the compiler and it allocates memory for the elements in the string literal used as initializer plus the null terminator. So, you got the desired result.

IMO,总是用后面的方法,省了很多时不时的头疼.

IMO, always use the later approach, saves a lot of headache from time to time.

这篇关于为什么当数组不包含空终止符时 strlen() 返回奇怪的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆