【发布时间】:2015-04-08 20:31:02
【问题描述】:
我正在研究指针,但我被下面的示例程序难住了。它应该是将char** 转换为char*,但我不明白程序背后的逻辑。程序在做什么?
#include <iostream>
using namespace std;
int main() {
char *notes[] = {"cpp","python","java","mariadb"};
void * base = notes; // notes and base, holds the address of note's first element
void * elemAddr = (char*) base + 3* sizeof(char *); // i didn't understand this line???
cout << *(char **)elemAddr; // and this line
return 0;
}
【问题讨论】:
-
我真的不明白这个例子的意义。试图通过混淆来教授一个概念似乎是一个糟糕的策略。
-
@RawN
char *notes[]衰减为char**,转换为void *base,转换为(char*)。 -
这段代码纯属邪恶,在暗处等着咬你。提示:
(char*)base + 3 * sizeof(char*)行也可以写成(char**) base + 3(后者更有意义)。然而,前者将base视为指向字符的指针(它只是保存一个地址),因此它需要添加3 * sizeof(char*)而不是仅添加3 来获取最后一个C 样式字符串的地址数组 -
绘制内存图可能会有所帮助。跟踪事物指向的位置,并记住指针添加的字节数取决于指针的类型。
-
@metis,一旦你有了
void*,初始类型就会丢失,除非你在别处有它。这是类型擦除的一种形式。此时的转换是从void*到char*。