c - C 中的指针和字符串输出

标签 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;
}

最佳答案

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

关于c - C 中的指针和字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088648/

相关文章:

c++ - C/C++ 中的 Aho-Corasick 算法(十六进制)

c - C 数组中偶数索引处的元素之和

java - int 数组或字符串数​​组或我错了

php - preg_replace() 和\n 在一个字符串中

c# - 为什么在 string 和 float 之间转换错误?

c - 从标准输入读取时出现问题 |奇怪的输出

c - Linux 是否允许将进程组 ID 重新分配给进程?

c - Linux:如何确定与 ioremap 返回的内容对应的 DMA 地址

c - 为什么 fgetc 太慢了?

arrays - 在golang中将数组作为参数传递