简体   繁体   English

K&R c 编程书第 2 版,第 2 章中的 strcat 示例

[英]K&R c programming book 2nd version, strcat example in chapter2

Initial I didn't intend to go deeper of this example, coz I think it's just several lines, not big deal, but when I use the hello world to test and verify my thought, I find something quite abnormal: here is the code part without too much comments:最初我并没有打算把 go 这个例子更深一些,因为我认为这只是几行,没什么大不了的,但是当我使用 hello world 测试和验证我的想法时,我发现有些异常:这里是代码部分没有太多评论:

#include<stdio.h>
void concatenate(char s[], char c[]);
int main(){
    char s[] = "hello";
    char c[] = "world";
    concatenate(s, c);
    printf("%s\n",s);
    return 0;
}
void concatenate(char s[], char c[]){
    int i, j;
    i = j = 0;
    while(s[i] != '\0')/* find the end of s*/
        i++;
    while((s[i++] = c[j++]) != '\0') /* copy c string */
        printf("%d,%c\n", i, s[i]);
    printf("0,%c\n", s[0]);
    printf("1,%c\n", s[1]);
    printf("2,%c\n", s[2]);
    printf("3,%c\n", s[3]);
    printf("4,%c\n", s[4]);
    printf("5,%c\n", s[5]);
    printf("6,%c\n", s[6]);
    printf("7,%c\n", s[7]);
    printf("8,%c\n", s[8]);
    printf("9,%c\n", s[9]);
    printf("10,%c\n", s[10]);
}

how to run it?如何运行它? I'm using ubuntu 64-bit 18.04 version===> cc concat.c the output:我正在使用 ubuntu 64 位 18.04 版本===> cc concat.c output:

在此处输入图像描述

在此处输入图像描述 From the screenshot, it is so hard to imagine why the output is like this, could anyone plz spend a bit of time explaining why it is this??从截图中,很难想象为什么output是这样的,谁能花点时间解释一下这是为什么? really appreciate it!真的很感激!

On one hand, there is something wrong in here:一方面,这里有问题:

Due to the post-increment of i, you should use:由于 i 的后增量,您应该使用:

  while((s[i++] = c[j++]) != '\0') /* copy c string */
        printf("%d,%c\n", i, s[i-1]);

instead of s[i] , otherwise you would print garbage values like this:而不是s[i] ,否则你会打印这样的垃圾值:

6,(
7, 
8,(
9,
10,4
0,h
1,e
2,l
3,l
4,o
5,w
6,o
7,r
8,l
9,d
10,

on the other hand, you are affecting c[j++] to s[i++] , thus copying the text 'hello' from c to s from index i which is 5 to the index 10 .另一方面,您将c[j++]影响到s[i++] ,因此将文本 'hello' 从cs从索引i到索引 5 到索引10 This allows for copying the content of c[] to s[] from the end of hello , making it containing helloworld\0 .这允许将c[]的内容从hello的末尾复制到s[] ,使其包含helloworld\0

A good reference, for a first thought can be to look at iso/iec doc section 6.7.8 example 8 (page 130).一个很好的参考,首先可以查看iso/iec 文档第 6.7.8 节示例 8(第 130 页)。

It is stated that:据称:

The contents of the arrays are modifiable arrays的内容是可修改的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM