如果字符串中间出现空字符怎么办? [英] What if a null character is present in the middle of a string?

查看:91
本文介绍了如果字符串中间出现空字符怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道字符串的结尾由空字符表示,但我无法理解以下代码的输出.

I understand that the end of a string is indicated by a null character, but i cannot understand the output of the following code.

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

int
main(void)
{
    char s[] = "Hello\0Hi";
    printf("%d %d", strlen(s), sizeof(s));
}

输出:5 9

如果 strlen() 在 o 的末尾检测到字符串的结尾,那么为什么 sizeof() 不做同样的事情呢?即使它不做同样的事情,不是 '\0' 一个 空字符(即只有一个字符),所以答案不应该是 8 吗?

If strlen() detects the end of the string at the end of o, then why doesn't sizeof() do the same thing? Even if it doesn't do the same thing, isn't '\0' A null character (i.e, only one character), so shouldn't the answer be 8?

推荐答案

sizeof 运算符不给你字符串的长度,而是它的操作数类型的大小.由于在您的代码中操作数是一个数组,sizeof 为您提供数组的大小,包括两个 null 字符.

The sizeof operator does not give you the length of a string but instead the size of the type of it's operand. Since in your code the operand is an array, sizeof is giving you the size of the array including both null characters.

如果是这样

const char *string = "This is a large text\0This is another string";
printf("%zu %zu\n", strlen(string), sizeof(string));

结果会大不相同,因为 string 是一个指针而不是数组.

the result will be very different because string is a pointer and not an array.

注意:对 size_t 使用 "%zu" 说明符,这是 strlen() 返回的内容,也是值的类型由 sizeof 给出.

Note: Use the "%zu" specifier for size_t which is what strlen() returns, and is the type of the value given by sizeof.

这篇关于如果字符串中间出现空字符怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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