比如说,我们正在做以下事情:
char* pc1;
char* pc2;
然后我们就可以做
pc1 = "STRING";
pc2 = "ANOTHERSTRING";
我的问题是,如果内存中 pc1
仅比 pc2
早 2 个字节并且它们发生冲突怎么办?当我们不知道它们不会碰撞/重叠时,为什么我们能够将字符串文字设置为指针并且具有无限长度?
编辑:我想问的是,如果 pc1
是说,内存中 pc2
之前的 16 个字节同时指向一个 300 字节长的字符串。但指针实际上指向内存中其他地方的字符串,所以我的问题现在很清楚了,谢谢大家。我并不是故意选择 pc1
作为 pc2
的后缀,但是,这看起来又是另一回事了。
最佳答案
我认为您可能对 pc1
和 pc2
的分配的作用感到困惑。这些语句没有将引用字符串的内容复制到pc1
和pc2
指向的内存位置。他们正在改变pc1
和pc2
指向的内存位置。为了明白我的意思,让我们向您的代码添加一些内容,使其成为一个完整的程序:
#include <stdio.h>
int main() {
char* pc1 = NULL;
char* pc2 = NULL;
printf("pc1 pointing to location in memory: %p\n", pc1);
printf("pc2 pointing to location in memory: %p\n", pc2);
pc1 = "STRING";
pc2 = "ANOTHERSTRING";
printf("pc1 pointing to location in memory: %p\n", pc1);
printf("pc2 pointing to location in memory: %p\n", pc2);
}
现在编译并运行它。当我在我的机器上这样做时,我得到以下输出:
pc1 pointing to location in memory: (nil)
pc2 pointing to location in memory: (nil)
pc1 pointing to location in memory: 0x5578b61a57b8
pc2 pointing to location in memory: 0x5578b61a57bf
pc1
和 pc2
首先指向“无”(NULL
或 nil
)。然后,在赋值语句之后,我们将它们指向内存中分别包含字符串“STRING”和“ANOTHERSTRING”的不同位置。
关于c - 如果字符串在内存中重叠怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353821/