我写了这段代码
#include <stdio.h>
int main()
{
char String[] = "Hello the world!";
char *pointer = String;
int i;
printf(" %s\n", pointer);
pointer = "Helllooooo the worlldddddd";
printf("Hello %s\n", pointer);
printf("Hello %s\n", String);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我无法理解这条线是如何工作的.
pointer = "Helllooooo the worlldddddd";
Run Code Online (Sandbox Code Playgroud)
但我得到了这个输出
Hello the world!
Hello Helllooooo the worlldddddd
Hello Hello the world!
Run Code Online (Sandbox Code Playgroud)
如您所见,它无法更改String值,但显示的字符数超过原始字符数.这不应该导致缓冲区溢出吗?不会破坏其他变量吗?
当你写行
pointer="Helllooooo the worlldddddd";
Run Code Online (Sandbox Code Playgroud)
你不是说"把数组指向pointer并用字符串覆盖它的内容"Helllooooo the worlldddddd"",而是"更改哪个字符串 pointer指向它,使它现在指向字符串" ""Helllooooo the worlldddddd".这说明了当您直接打印时看到打印出来的原始字符串的原因String- 您从未真正修改过它.因此,您无需担心此处的数组溢出,因为您实际上并未向其中写入任何内容.
另一方面,如果你写了
strcpy(pointer, "Helllooooo the worlldddddd");
Run Code Online (Sandbox Code Playgroud)
实际上它会将新字符串的内容复制到指向的缓冲区中pointer,然后你会有一个缓冲区溢出,这将是一个问题.但请注意,这是一个非常不同的操作,明确表示"请将此字符串的内容复制到此位置",而不是"更改此指针指向的位置".
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |