這個問題在這里已經有了答案: printf 輸出垃圾而不是特定字符 2 個答案 昨天關門。
我寫了這段代碼:
#include<stdio.h>
#include<stdlib.h>
int main(){
char* test=malloc(8);
for(char i=0;i<8;i )
test[i]='A' i;
printf("%s",test);
return 0;
}
當我運行它時,我希望輸出是:
ABCDEFGH
但最后出現了一些額外的字符。
uj5u.com熱心網友回復:
正如其他人在評論部分已經指出的那樣,當使用帶有 的%s轉換格式說明符時printf,您必須將指向以空字符結尾的字串的指標作為引數傳遞。但是,您的字串不是以空值結尾的。
您必須為終止空字符分配一個額外的位元組并添加一條寫入該字符的陳述句:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
//allocate 9 bytes instead of 8, because we need room for
//the terminating null character
char* test = malloc( 9 );
for ( char i = 0; i < 8; i )
test[i] = 'A' i;
//add this line which writes the terminating null character
test[8] = '\0';
printf( "%s", test );
return 0;
}
該程式具有以下輸出:
ABCDEFGH
實際上,我上面所說的并不完全正確。通過將列印的字符數限制為 8 個,也可以在沒有終止空字符的情況下解決該問題:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char* test = malloc( 8 );
for ( char i = 0; i < 8; i )
test[i] = 'A' i;
printf( "%.8s", test );
return 0;
}
這樣,就可以列印非空終止的字串。有關詳細資訊,請參閱檔案printf。但是,除非您有特殊原因,否則通常不建議使用不以 null 結尾的字串。通常建議您的所有字串都以空字符結尾。
還值得一提malloc的是,在嘗試使用分配的記憶體緩沖區之前,您通常應該檢查函式的回傳值是否成功:
char* test = malloc( 9 );
if ( test == NULL )
{
fprintf( stderr, "Memory allocation failure!\n" );
exit( EXIT_FAILURE );
}
//Memory allocation was successful and the memory buffer can
//now be used.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487157.html
