【发布时间】:2019-09-04 20:46:42
【问题描述】:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
char **p;
p = (char **)malloc(100);
p[0] = (char *)"Apple"; // or write *p, points to location of 'A'
p[1] = (char *)"Banana"; // or write *(p+1), points to location of 'B'
cout << *p << endl; //Prints the first pointer
}
在上面的代码中:
p[0] = (char *)"Apple";
似乎会自动保留内存。没有malloc。这是 C/C++ 标准还是特定于编译器的?
更新 1 我实际上对它在 C 和 C++ 中的表现很感兴趣。只是我没有为上面的代码安装C编译器,所以我使用了C++。
所以 p 是在指向 HEAP 中的内存块(数组)的 STACK 上分配的,其中每个元素都指向(是指针)指向 DATA 段中的文字?哇!
【问题讨论】:
-
string literals 是一个很好的起点,至少对于 C++ 而言。
-
这不是 c 这是 c++。在 C++ 中,您不能将字符串文字转换为非 const char *
-
@Jean-FrançoisFabre 是的,您可以,就像 OP 在此示例中所做的那样。未定义的行为仅在您尝试修改它指向的数据时出现。
-
您正在分配一个指向常量的指针数组。如果指向的字符串是动态的,事情就会变得更有趣。此外,很少有理由在 C++ 中进行这种类型的字符串存储。 (C 是另一回事。)
-
这是 C++ 中未定义的行为,您可以使用
new而不是malloc
标签: c++ pointers pointer-to-pointer