我想連接從歌曲閃爍閃爍的隨機數行。發送出去之前進入緩衝區,因爲我需要計算緩衝區的大小。C - 如何將一個字符串數組連接到一個緩衝區?
我的代碼:
char temp_buffer[10000];
char lyrics_buffer[10000];
char *twinkle[20];
int arr_num;
int i;
twinkle[0] = "Twinkle, twinkle, little star,";
twinkle[1] = "How I wonder what you are!";
twinkle[2] = "Up above the world so high,";
twinkle[3] = "Like a diamond in the sky.";
twinkle[4] = "When the blazing sun is gone,";
twinkle[5] = "When he nothing shines upon,";
srand(time(NULL));
arr_num = rand() % 5;
for (i=0; i<arr_num; i++);
{
sprintf(temp_buffer, "%s\n", twinkle[i]);
strcat(lyrics_buffer, temp_buffer);
}
printf("%s%d\n", lyrics_buffer, arr_num);
我當前的代碼只打印1線,甚至當我得到一個數字大於0
你是否在任何地方初始化'lyrics_buffer'?如果你不這樣做並且它是一個局部變量,那麼在'strcat'中使用它會導致*未定義的行爲*。 –
@JoachimPileborg是它的一個局部變量。我是否也應該在主體中聲明它? –
'for(i = 0; i'%6' –
BLUEPIXY