I am studying pointers, but I have been stumped by the example program below. It is supposed to be doing a conversion of char**
to char*
, but I don't understand the logic behind the program. What is the program doing?
#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;
}
These lines:
char *notes[] = {"cpp","python","java","mariadb"};
void * base = notes;
void * elemAddr = (char*) base + 3* sizeof(char *);
cout << *(char **)elemAddr;
are an obfuscated equivalent of:
char *notes[] = {"cpp","python","java","mariadb"};
cout << notes[3];
Explanation:
void * base = notes;
void * elemAddr = (char*) base + 3* sizeof(char *);
is the same as:
char * base = (char*)notes;
char * elemAddr = base + 3 * sizeof(char *);
Since pointers are usually of the same size, those lines are kind of the same as:
char ** base = notes;
char ** elemAddr = base + 3;
which makes elemAddr == ¬es[3]
. That leads to the line
cout << *(char **)elemAddr;
to be the same as
cout << notes[3];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With