本文介绍了SIZEOF VS STRLEN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdio.h"
#include "string.h"

main()
{

    char string[] = "october"; // october is 7 letters

    strcpy(string, "september"); // september is 9 letters

    printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string));

    return 0;
}

输出:

九月的大小为8,长度是9

是不是有什么毛病我的语法还是什么?

Is there something wrong with my syntax or what?

推荐答案

的sizeof 的strlen()做不同的东西。在这种情况下,你的宣言

sizeof and strlen() do different things. In this case, your declaration

char string[] = "october";

是相同的

char string[8] = "october";

所以编译器可以告诉大家,字符串的大小为8它这样做是在编译时。

so the compiler can tell that the size of string is 8. It does this at compilation time.

然而,的strlen()计数的字符在运行时字符串中的数字。所以,你以后叫的strcpy()字符串现在包含九。 的strlen()计数的人物和他们的发现9。需要注意的是你还没有分配足够的空间用于字符串举办九。这是不确定的行为。

However, strlen() counts the number of characters in the string at run time. So, after you call strcpy(), string now contains "september". strlen() counts the characters and finds 9 of them. Note that you have not allocated enough space for string to hold "september". This is undefined behaviour.

这篇关于SIZEOF VS STRLEN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:34