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

查看:308
本文介绍了当数组不包含空终止符时,为什么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天全站免登陆