這個問題在這里已經有了答案: 將非空終止字串傳遞給 printf 會導致意外值 6 個答案 使用不帶空字符的 printf 列印字串 [重復] 1 個答案 如何制作一個非空終止的c字串? (7 個回答) C 中的 '\0' 和 printf() (9 個答案) 不在字串中使用空終止有什么影響? (3 個回答) 2天前關閉。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[40]="Who are you tell me that I can not code?";
char c=s[8];
char st[2];
st[0]=s[0],st[1]=s[1];
printf("%s \n",st);
return 0;
}
為什么在我列印 st 時它也會列印我的原始字串's'?
輸出:-
WhWho are you tell me that I can not code??
Process returned 0 (0x0) execution time : 0.048 s
Press any key to continue.
uj5u.com熱心網友回復:
s不是正確的 C 字串,因為它正好有 40 個位元組和 40 個字符。C 字串必須有一個空終止位元組。您應該將其定義為:
char s[] = "Who are you tell me that I can not code?";
st對于您將其定義為存盤 2 個字符的 2 個位元組陣列,存在同樣的問題。您應該定義st為 3 個位元組的陣列,并'\0'在st[2].
這兩個問題都可能導致未定義的行為。第二個是作為你傳遞st的格式,它需要一個正確的 C 字串指標printf()。%s
這是修改后的版本:
#include <stdio.h>
int main() {
char s[] = "Who are you tell me that I can not code?";
char st[3];
st[0] = s[0];
st[1] = s[1];
st[2] = '\0';
printf("%s\n", st);
return 0;
}
請注意,您還可以printf使用精度欄位列印子字串:
#include <stdio.h>
int main() {
char s[] = "Who are you tell me that I can not code?";
// print the 3 characters at offset 4
printf("%.3s\n", st 4);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/490491.html
上一篇:從字串中提取血壓值
