c - 理解 C 指针

标签 c pointers

#include <stdio.h>
#include <string.h>

int main(){


// char* is a pointer
    char str_a[20];
    char *pointer;
    char *pointer2;

    strcpy(str_a, "Hello, world\n");
    pointer = str_a;
    printf(pointer);

    pointer2 = pointer + 2;
    printf(pointer2);
    strcpy(pointer2, "y you guys!\n");
    printf(pointer);
}

你好,我正在看一本书,遇到了一个解释我无法理解的指针的程序。书上好像没有说为什么会这样,也就是说我得去别处查阅才能更好地理解。上面的代码生成以下输出:

Hello, world! (pointer)
llo, world!   (pointer2)
Hey you guys! (pointer)

我无法理解的是,变量 pointer 的最后一次更改是在第 8 行。但是可以清楚地看到 pointer 的值在最后一次发生了变化输出行。

我希望 pointer2 的值在输出的第二行是 He 而不是 llo, world!。我唯一能想到的 - 是在第 14 行,当指定 + 2 时,指针的前两个字节被截断(或者剩余字节被截断,并且前两个字节在 中保持不变指针?)

但事实并非如此 - 因为当我在 pointer2 = pointer + 2 下面添加 printf(pointer) - 输出是“Hello, world!”再次而不是“他”

最佳答案

首先 pointerpointer2 没有被声明为指针,在这些变量之前应该有一个 '*' 来声明它们为指针。即使这是书中的内容,也是不正确的。

What I fail to understand is that the last change to the variable pointer is on line 8. Yet the value of pointer can clearly be seen to change in the last line of output.

是的!这就是指点的意义! pointer2pointer 具有相同的地址,但加上 2 个元素(记住数组变量包含该数组第一个变量的地址),如“pointer2 = pointer + 2 ;"因此,"strcpy(pointer2, "y you guys!\n");"指令将开始复制“He”之后的字符,因为 pointer2 指向第一个“l”。

关于c - 理解 C 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41685123/

相关文章:

android - 无法弄清楚为什么此代码在发送数据包数据时会导致 SIGSEGV

c - (新手) strstr() 返回带有无符号参数的 null

c++ - 返回指针 c

生成钟形曲线的代码仅在偶数索引处创建数据。为什么?

c - __attribute__((OS_main)) 在 AVR 中导致奇怪的行为

c - 取消引用指向 void 数组的指针

c - `*a =` 和 `= *a` 有什么区别?

c - 为什么类型在 C 中的这个值交换代码中不匹配?

C - 未选择的选项

c++ - 了解从二进制文件中提取频率以创建哈夫曼树的逻辑