Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion of char *notes[] = {"Ab", "F#", "B", "Gb", "D"}; and char**

Tags:

c++

pointers

I am really confused this type of pointer definition:

char *notes[] = {"Ab", "F#", "B", "Gb", "D"};`. 

I understand that notes here is an array of pointer to char, which I understand as notes' elements should all be the addresses of char typed variables. Where am I wrong? So how does this work?

#include<iostream>
#include<string>

using namespace std;

int main()
{
    char *notes[] = {"Ab", "F#", "B", "Gb", "D"};
    cout << *(char**)(notes+2);
}

Also what is the char** cast there and what is its significance?

like image 324
daydayup Avatar asked Dec 04 '22 03:12

daydayup


1 Answers

In this sense, char *notes[] means notes[] is an array pointer to char

It means that nodes is an array of char*, i.e. an array of character pointers.

notes[] 's elements should all be the addresses of char typed variables.

C implicitly converts string literals (i.e. character sequences enclosed in double quotes) to null-terminated C strings, and produces addresses of the initial character as pointers for adding to the array. That is how the array gets initialized.

Here is an example of how the data could be placed in memory:

Address Value Character
------- ----- ---------
1000000    65 A
1000001    98 b
1000002    00 NULL terminator
1000003    70 F
1000004    35 #
1000005    00 NULL terminator
1000006    66 B
1000007    00 NULL terminator
1000008    71 G
1000009    98 b
1000010    00 NULL terminator
1000011    68 D
1000012    00 NULL terminator

Then your array of pointers will be initialized as follows:

notes = {1000000, 1000003, 1000006, 1000008, 1000011};

Note: Above layout is only an example. String literals may not necessarily be placed in memory back-to-back.

like image 160
Sergey Kalinichenko Avatar answered Dec 06 '22 17:12

Sergey Kalinichenko