gpt4 book ai didi

c++ - 指针,将 char ** 转换为 char *

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:36 25 4
gpt4 key购买 nike

我正在研究指针,但我被下面的示例程序难住了。它应该是将 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;
}

最佳答案

这些行:

char *notes[] = {"cpp","python","java","mariadb"};
void * base = notes;
void * elemAddr = (char*) base + 3* sizeof(char *);
cout << *(char **)elemAddr;

是混淆后的等价物:

char *notes[] = {"cpp","python","java","mariadb"};
cout << notes[3];

解释:

void * base = notes; 
void * elemAddr = (char*) base + 3* sizeof(char *);

等同于:

char * base = (char*)notes; 
char * elemAddr = base + 3 * sizeof(char *);

由于指针通常大小相同,因此这些行类似于:

char ** base = notes; 
char ** elemAddr = base + 3;

这使得 elemAddr == &notes[3]。这导致线

cout << *(char **)elemAddr;

相同
cout << notes[3];

关于c++ - 指针,将 char ** 转换为 char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com