Ste*_*eve 12 c string cstring null-terminated
我有一个char数组缓冲区,我用它来存储用户将逐个输入的字符.我下面的代码有效,但有一些我无法弄清楚的故障:
有人可以向我解释发生了什么,也许我可以解决这个问题?谢谢.
char Buffer[8]; //holds the byte stream
int i=0;
if (/* user input event has occurred */)
{
Buffer[i] = charInput;
i++;
// Display a response to input
printf("Buffer is %s!\n", Buffer);
}
Run Code Online (Sandbox Code Playgroud)
输出:
tagBuffer is 1??w! tagBuffer is 12?w! tagBuffer is 123w! tagBuffer is 1234! tagBuffer is 12345! tagBuffer is 123456=! tagBuffer is 1234567! tagBuffer is 12345678!
tagBuffer是123456789!
传递给printf()函数的唯一事情是指向字符串第一个字符的指针.printf()无法知道数组的大小.(它甚至不知道它是否是一个实际的数组,因为指针只是一个内存地址.)
printf()和所有标准c字符串函数假定字符串末尾有一个0.例如,printf()将在内存中保持打印字符,从传递给函数的char开始,直到它达到0.
因此,您应该将代码更改为以下内容:
char Buffer[9]; //holds the byte stream
int i=0;
if( //user input event has occured )
{
Buffer[i] = charInput;
i++;
Buffer[i] = 0; // You can also assign the char '\0' to it to get the same result.
// Display a response to input
printf("Buffer is %s!\n", Buffer);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51056 次 |
最近记录: |