C中的指针和字符串输出

时间:2015-03-16 23:19:33

标签: c arrays string pointers output

我试图理解为什么以下代码产生 BCD123 123 的输出。

void f(char *p)
{
    *p += 1;
}

int main()
{
    int i;
    char a[] = "ABC" "123";
    char *p = a;

    for (i = 0; i < 3; i++)
        f(p++);

    printf("%s ", a);

    printf("%s ", p);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

void f(char *p)
{
    *p += 1;
}

为传入的字符添加1。'A'+ 1 ='B'等。查看ascii表http://www.asciitable.com/

第2部分

   char a[] = "ABC" "123";
// is the same as 
   char a[] = "ABC123";
      for (i = 0; i < 3; i++)
            f(p++); <<<<===== moves p along the string 3 places (once for each loop)

        printf("%s ", a);

        printf("%s ", p);  <<< p now points at 4th char