简体   繁体   English

我可以在C ++中使用这个C风格的字符串获得一些帮助吗?

[英]Can I get some assistance with this C style string in C++?

I'm trying to understand un-managed code. 我正在尝试理解未托管的代码。 I come from a background of C# and I'm playing around a little with C++. 我来自C#的背景,我正在玩C ++。

Why is that this code: 为什么这个代码:

#include <iostream>

using namespace std;

int main()
{
    char s[] = "sizeme";

    cout << sizeof(s);

    int i = 0;
    while(i<sizeof(s))
    {
        cout<<"\nindex "<<i<<":"<<s[i];
        i++;
    }
    return 0;
}

prints out this: 打印出来:

7
index 0:s
index 1:i
index 2:z
index 3:e
index 4:m
index 5:e
index 6:

???? ????

Shouldn't sizeof() return 6? sizeof()不应该返回6吗?

C strings are "nul-terminated" which means there is an additional byte with value 0x00 at the end. C字符串是“nul-terminated”,这意味着在结尾处有一个值为0x00的附加字节。 When you call sizeof(s) , you are getting the size of the entire buffer including the nul terminator. 当您调用sizeof(s) ,您将获得整个缓冲区的大小, 包括 nul终止符。 When you call strlen(s) , you are getting the length of the string contained in the buffer, not including the nul. 当你调用strlen(s) ,你得到缓冲区中包含的字符串的长度 ,不包括nul。

Note that if you modify the contents of s and put a nul terminator somewhere other than at the end, then sizeof(s) would still be 7 (because that's a static property of how s is declared) but strlen(s) could be somewhat less (because that's calculated at runtime). 请注意,如果修改s的内容并将nul终止符放在除结尾之外的某处,那么sizeof(s)仍然是7(因为这是声明s的静态属性)但是strlen(s)可能有点少(因为这是在运行时计算的)。

No, all trings in C are terminated by the null character (ascii 0). 不,C中的所有转义都以空字符(ascii 0)结束。 So s is actually 7 bytes 所以s实际上是7个字节

s i z e m e \0

这是因为C字符串包含值0 (或'\\0' )作为标记字符串结尾的最后一个字符。

s是7个字节,6个用于字符串,1个用于空终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM