【问题标题】:Why the strcat function move the pointer to the next character?为什么 strcat 函数将指针移动到下一个字符?
【发布时间】:2021-04-12 13:55:34
【问题描述】:

所以,我的问题很简单,我不知道为什么第一段代码不能正常工作。 该程序从管道中读取一个 12 个字符的字符串,并且 strcat 函数每次执行该函数时都会将 buff 的指针从第一个字符移动到下一个字符,因此经过几次交互后,read 函数使程序失败,因为缓冲区是不够大了。 使用 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] = '\0'; 
        }
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] = '\0';       
        }

【问题讨论】:

  • 查找strcatsprintf的描述!
  • while(n = read(fd[0],buff,12) > 0) 也是错误的。查找=>的优先级
  • 还有write(1,output,13);:如果你先问n,为什么要写13个字节?
  • 移动的不是第一个字符而是最后一个字符。
  • @PaulOgilvie fd 未在此处声明。您是如何获得这些知识的?

标签: c string strcat


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    sprintf

    strcat%s 说明符需要 字符串,这意味着 C 中的“空终止字符序列”。

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

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

    【讨论】:

    • buf[n]='\0'; 你的意思是?
    • 我认为不需要buff[0] = '\0'(使用n时)
    • @PaulOgilvie buff[0] = '\0' 即使没有n 也不需要(如果在循环后不使用buff),因为buff[0] 无论如何都会被成功的read 覆盖。
    猜你喜欢
    • 2014-08-06
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2020-02-03
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多