我知道很多人问过这个问题,但我仍然有一些疑问。 我读到了这篇文章:
char *string = "mystring";
如果我试图这样做,则将其设为只读字符数组:
string[0] = 'l';
我会收到一个错误。 当我写下:
char string[] = "mystring";
它保存在堆栈上,仅保存在当前范围内。 那么 char* 呢?它保存在堆上吗?或者在堆栈上?
当我尝试写作时:
char *string = "mystring";
然后:
string = "mystring2";
它有效,但是旧的“mystring”数组发生了什么?这样做是否会导致内存泄漏?
最佳答案
what about the char*? is it saved on the heap? or on the stack?
char*
保存在堆栈中。但这只是一个指针。实际的字符串数据将存储在程序的可执行文件中(这种情况发生在编译程序时,不是 char *string = "mystring";
将其放在那里)。对 char*
的赋值会使用程序二进制文件中 "mystring"
的地址对其进行初始化。
it worked, but what happened to the old "mystring" array? is there a memory leak caused by doing this?
您的可执行文件将包含"mystring";
和"mystring2"
的内容。当您执行 string = "mystring2";
时,您使该指针从指向一个指针变为指向另一个指针。这里没有内存泄漏。
关于c - 在C语言中,char*和char[]有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215966/