我有一個一般的理解問題!這是我的代碼:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>
int main() {
// read user input
char input[64] = {0};
read(0, input, 64);
printf("You've entered ");
printf(input);
char newbuf[128];
char smallbuf[8];
// copy into smallbuf 8 bytes of input
memcpy(smallbuf, input, 8);
// send smallbuf of 8 bytes as string into newbuf
sprintf(newbuf, "%s", smallbuf);
// print newbuf
printf(&newbuf[0]);
return 0;
}
我用 7 個字符得到的行為是可以的,它確實列印了 7 個字符:
$ gcc a.cpp -o a.out && ./a.out
1234567
You've entered 1234567
1234567
1234567
但是對于 8 個字符,它會列印出更多字符,我想知道為什么要這樣做:
$ gcc a.cpp -o a.out && ./a.out
12345678
You've entered 12345678
1234567812345678
謝謝你為我解釋!:)
uj5u.com熱心網友回復:
代碼試圖列印一個字符陣列,就好像它是一個導致未定義行為的字串。
肯定不包含空字符,因此它不是字串。需要一個指向string的匹配指標。smallbuf[]
"%s"
要么占空字符
char smallbuf[8 1];
memcpy(smallbuf, input, 8);
smallbuf[8] = '\0';
printf("%s", smallbuf);
或以精度限制輸出。列印最多 N 個字符或空字符的字符陣列。
char smallbuf[8];
memcpy(smallbuf, input, 8);
printf("%.8s", smallbuf);
類似的問題適用于 printf(input);
不要代碼printf(input);作為可能會導致不確定的行為時,input[]含有%。
// printf(input);
printf("%s", input);
更好的代碼會檢查 的回傳值read(0, input, 64)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327479.html
上一篇:C中的字典,函式作為值
下一篇:Python到C浮點不精確
