为什么 strcat 函数将指针移动到下一个字符?

Why the strcat function move the pointer to the next character?

所以,我的问题很简单,我不知道为什么第一段代码不能正常工作。 该程序从管道中读取一个 12 个字符的字符串,每次执行该函数时,strcat 函数都会将 buff 的指针从第一个字符移动到下一个字符,因此在几次交互之后,读取函数使程序失败,因为缓冲区是不够大了。 使用 sprintf 函数和另一个字符串解决了这个问题,但我不明白是什么导致了这个问题。 感谢您的帮助。

int n; 
char buff[15];
close(fd[1]);
    while(n = read(fd[0],buff,12) > 0){      
        strcat(buff,"\n");
        write(1,buff,13); 
        buff[0] = '[=10=]'; 
        }
int n; 
char buff[15];
char output[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){      
            sprintf(output,"%s\n",buff); 
            write(1,output,13); 
            buff[0] = '[=11=]';       
        }

strcat%s sprintf 的说明符需要 strings,这意味着“null-terminted C 中的字符序列”

如果不能保证管道中的内容以 null 终止,则必须添加终止 null 字符。

int n;
char buff[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){
    buff[12] = '[=10=]'; /* add terminating null-character */
    strcat(buff,"\n");
    write(1,buff,13);
    buff[0] = '[=10=]';
}
int n;
char buff[15];
char output[15];
close(fd[1]);
while(n = read(fd[0],buff,12) > 0){
    buff[12] = '[=11=]'; /* add terminating null-character */
    sprintf(output,"%s\n",buff);
    write(1,output,13);
    buff[0] = '[=11=]';
}

正确的代码终止缓冲区,假设它包含一个字符串:

int n;
char buff[15];
close(fd[1]);
while((n = read(fd[0],buff,12)) > 0){
    buff[n] = '[=10=]'; /* add terminating null-character */
    strcat(buff,"\n");
    write(1,buff,n+1);
}

int n;
char buff[15];
char output[15];
close(fd[1]);
while((n = read(fd[0],buff,12)) > 0){
    buff[n] = '[=11=]'; /* add terminating null-character */
    sprintf(output,"%s\n",buff);
    write(1,output,n+1);
}
  • 注意分配给 n
  • 的额外 ()
  • 注意n的使用,实际读取的字符数
  • 并注意,正如迈克所说,字符串的终止。