Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers, conversion of char ** to char *

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;
}
like image 250
metis Avatar asked Jan 09 '23 14:01

metis


1 Answers

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 == &notes[3]. That leads to the line

cout << *(char **)elemAddr;

to be the same as

cout << notes[3];
like image 133
R Sahu Avatar answered Jan 14 '23 19:01

R Sahu