我在使用動態記憶體理解 C 中的字串宣告時遇到了一些麻煩。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *putText(){
char *s=(char *) malloc(256 sizeof(char));
for(int i=0; *(s i); i ) *(s i)=getchar();
return s;
}
void main(){
printf("Write the text: ");
char *s=putText();
printf("%s", s);
}
在這個函式中,我試圖getchar()在 for 回圈中宣告字串,但是當我嘗試列印字串時,它總是在第三個字符處停止。我還是個新手,所以我可能犯了一些錯誤。有人可以幫忙嗎?
uj5u.com熱心網友回復:
此宣告中分配的記憶體
char *s=(char *) malloc(256 sizeof(char));
可以包含任何垃圾。
所以for回圈中的條件
for(int i=0; *(s i); i ) *(s i)=getchar();
沒有意義。
相反,您可以撰寫例如
int c;
for ( size_t i=0; i 1 < 256 && ( c = getchar() ) != EOF && c != '\n'; i )
{
*( s i ) = c;
}
*( s i ) = '\0';
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393258.html
上一篇:結構不保存新值
