关于unicode乱码的快速问题...... [英] Quick question regarding unicode gibberish...
问题描述
所以,我正在使用以下方法打印数组中的每个元素:
So, I''m using the following method to print each element in an array:
char* a[] = {"this","is","a","test","string"};
int i = 2;
while(a[i])
{
std::cout << a[i - 2] << std::endl;
i++;
}
现在,我实施-2的原因是因为当我没有不包括''-2'',每个元素都会打印,但最后两行会是一些ascii unicode乱码。任何人都可以解释一下这种乱码是什么以及为什么我的-2是必要的?我的代码工作我只是想知道它为什么有效。谢谢!
Now, the reason I implement the ''-2'' is because when I didn''t include the ''-2'', each element would print, but the last two lines would be some ascii unicode gibberish stuff. Could anyone explain what that gibberish is and why my ''-2'' is neccessary? My code works I''m just interested in knowing why it works. Thanks!
推荐答案
你应该写:
You should write:
char* a[] = {"this","is","a","test","string", 0};
否则你的while循环将在指针数组的末尾运行,它在那里看到的是纯粹的运气。
或者你使用这样的for循环:
otherwise your while loop is going to run off the end of the pointer array and it is pure luck what it sees there.
Or you use a for loop like this:
#define COUNT(x) (sizeof(x)/sizeof(x[0]))
...
for (int i=0; i < COUNT(a); ++i)
...
首先,没有Unicode乱码这样的东西。完全不参与Unicode(我的印象是你对Unicode没有任何线索,这不好。:-))
代码和解释一样奇怪。不,它也不是有效。你的结果是不可预测的。
让我们给你的数组元素编号:
First of all, there is no such thing as "Unicode gibberish". Unicode is not involved at all (I have an impression that you don''t have a clue on Unicode, which is no good. :-))
The code is exactly as weird as explainable. No, it is not "working", too. Your result is unpredictable.
Let''s number the elements of your array:
char* a[] = {
"this", // 0
"is", // 1
"a", // 2
"test", // 3
"string" // 4
// something else // 5 you always have something past the last element, does not have to be null
// something else
// ...
};
你从2开始,这是a ,但在打印实际上移位-2,所以你打印这然后增加。由于一些随机的原因,你得到一个null元素超过数组,你的循环停止。正如CHill60正确解释的那样,没有什么可以保证你在数组数据之外的任何地方都有null(0)。其他一些数据也在那里。在其他情况下(例如,在构建的不同配置中),您可以获得异常,例如一般保护错误。
我不写正确的代码因为1)你没有问过它; 2)因为你没有解释预期结果应该是什么。
这篇关于关于unicode乱码的快速问题......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!