繁体   English   中英

这段代码如何启动索引为1的C风格字符串?

[英]How does this code start a C-style string with index 1?

const int MAXN = 100;
char s[MAXN];
cin >> s + 1;
for (int i = 1; i <= strlen(s); i++) {
    cout << s[i];
}

我的朋友写了这段代码。 我不知道cin >> s + 1究竟是什么意思。 在这种情况下,C风格的字符串以索引1开头,以索引strlen结束。 我很困惑,因为C风格的字符串以0开头并以strlen - 1结尾。

C风格的字符串只是一个字节数组。 您可以根据需要索引数组(只要您保持在其范围内)。 问题中的代码只是忽略数组的第一个元素(索引0处的元素)。

如果为表达式s + 1引入别名,也许你可以更好地理解代码:

const int MAXN = 100;
char s[MAXN];
char *t = s + 1;
cin >> t;
for (int i = 1; i <= strlen(t); i++) {
    cout << s[i]; // which is the same as t[i-1]
}

请注意,条件i <= strlen(s + 1)是可疑的:它将在输出中包含终止NUL字符。

char[]可以用作char* ,所以做s+1只是说从s[1]++s开始读取,所以使用std::cin >> s+1会让s[0]未被初始化。

我们应该讨论原始代码吗?

const int MAXN = 100;
char s[MAXN];
cin >> s + 1;
for (int i = 1; i <= strlen(s + 1); i++) {
    cout << s[i];
}

或编辑后

const int MAXN = 100;
char s[MAXN];
cin >> s + 1;
for (int i = 1; i <= strlen(s); i++) {
    cout << s[i];
}

如果s[0]等于0则第二个可以得到0形式的strlen(s) 此外,它跨过结束NUL字符。

在第一个中, cin >> s + 1; 从标准输入读取数据并将其从s[1] for循环从1开始,因此第一个输出的字符将来自s[1] 唯一棘手的部分是i <= strlen(s + 1) 通常我们写i < strlen(s) 因为有strlen(s + 1) i不会达到NUL字符。

假设在cin之后我们得到“_ABCD0”( 0表示NUL字符 - 不是0位, _表示未触及的s[0] )。 strlen(s + 1)将产生4,所以最后一个索引,其中i < strlen(s + 1)将是3,它指向字母C.我们可以通过i < strlen(s + 1) + 1i <= strlen(s + 1)来纠正这个问题i <= strlen(s + 1)

它可以工作,但它极大地增加了“一个错误”的概率。 非常不推荐。

cin >> s + 1; 可能导致缓冲区溢出。 使用std::string而不是原始指针。

暂无
暂无

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

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