问题描述
如图所示,本来是一个长度为4的字符数组,用%c手动一个一个输出是正常显示,但是用%s直接输出这个字符数组就出现输出位数并不是4,这是什么原因呢?是这个字符数组的后面没有带上0吗?遇到这种情况有什么简便的方法快速输出字符串吗?(万一有个长度几百的字符数组要输出难道我得手动一个一个用字符数组成员拼接吗?)
#include <stdio.h>#include <stdint.h>#include <stdlib.h>typedef struct WAV_header { char ChunkID[4]; /* 'RIFF' */ uint32_t ChunkSize; /* 36 + Subchunk2Size */ char Format[4]; /* 'WAVE' */ /* sub-chunk 'fmt' */ char Subchunk1ID[4]; /* 'fmt ' */ uint32_t Subchunk1Size; /* 16 for PCM */ uint16_t AudioFormat; /* PCM = 1*/ uint16_t NumChannels; /* Mono = 1, Stereo = 2, etc. */ uint32_t SampleRate; /* 8000, 44100, etc. */ uint32_t ByteRate; /* = SampleRate * NumChannels * BitsPerSample/8 */ uint16_t BlockAlign; /* = NumChannels * BitsPerSample/8 */ uint16_t BitsPerSample; /* 8bits, 16bits, etc. */ /* sub-chunk 'data' */ char Subchunk2ID[4]; /* 'data' */ uint32_t Subchunk2Size; /* data size */} Wav_header_t;typedef struct WAV_block_header { char blockID[4]; /* 'data' */ uint32_t blockSize; /* data size */} Wav_block_header_t;int main(){ FILE *fp = NULL; Wav_header_t header; Wav_block_header_t block_header; fp = fopen('test.wav', 'rb'); if (!fp) {printf('can’t open audio filen');exit(1); } fread(&header, 1, sizeof(Wav_header_t), fp);// printf('length:%d(10),0x%x, nn', sizeof(struct WAV_Format), sizeof(struct WAV_Format)); // 44 printf('ChunkID t%c%c%c%cn', header.ChunkID[0], header.ChunkID[1], header.ChunkID[2], header.ChunkID[3]); printf('ChunkSize t%dn', header.ChunkSize); printf('Format t%sn', header.Format); printf('Subchunk1ID t%xn', header.Subchunk1ID); printf('Subchunk1Size t%dn', header.Subchunk1Size); printf('AudioFormat t%dn', header.AudioFormat); printf('NumChannels t%dn', header.NumChannels); printf('SampleRate t%dn', header.SampleRate); printf('ByteRate t%dn', header.ByteRate); printf('BlockAlign t%dn', header.BlockAlign); printf('BitsPerSample t%dn', header.BitsPerSample); printf('Subchunk2ID t%sn', header.Subchunk2ID); printf('Subchunk2Size t%dn', header.Subchunk2Size); printf('n');fread(&block_header, 1, sizeof(Wav_block_header_t), fp); printf('blockID t%sn', block_header.blockID); printf('blockSize t%dn', block_header.blockSize);}
问题解答
回答1:C语言的字符串结尾结束用’0’表示这个数组ChunkID[4]应该申明为ChunkID[5],然后填值时,在最后结束加上’0’,在这个例子里是ChunkID[4] = ’0’,就可以用'%s'输出字符串了.