-2

Hello can someone please tell me how this is possible in c++.

int main(){
  char *names[4]= {
  "Dany", "Emily", "Eric", "Alex"};
   .....}

it looks like they're initializing an array of pointers of size 4 and type char, but I'm not sure what its pointing to (4 different arrays of type char?) and if so is this the right declaration since we did not create an array to store the characters in each string? any explanation would be greatly appreciated :D

2 Answers2

1

In your code-snippet you defined a local array (explicit count given as 4 elements) which contains pointers to const string-literals.

Let's check the assembly of your code, if you want to go a level deeper (created with x86 gcc 4.9.2)

.LC0:
    .string "Dany"
.LC1:
    .string "Emily"
.LC2:
    .string "Eric"
.LC3:
    .string "Alex"
main:
    push    rbp
    mov rbp, rsp
    mov QWORD PTR [rbp-32], OFFSET FLAT:.LC0
    mov QWORD PTR [rbp-24], OFFSET FLAT:.LC1
    mov QWORD PTR [rbp-16], OFFSET FLAT:.LC2
    mov QWORD PTR [rbp-8], OFFSET FLAT:.LC3
    mov eax, 0
    pop rbp
    ret

Each binary/executable is organized in different segments [1] page 15. One part is for global variables, one is for the code, and another one is for read-only data (.rodata section), ... . As you can see, the assembly contains the 4 defined string-literals which go in the read-only section (see label .LC(0-9))

FYI: String-literals (actually everything) in the read-only section are const and must be declared as const. Trying to modify this section leads to undefined behavior.

const char* names[4]= {"Dany", "Emily", "Eric", "Alex"};
HelloWorld
  • 2,392
  • 3
  • 31
  • 68
1

Although many compilers tolerate it by default you have an error because you have non const char pointers pointing to const character arrays.

You should declare the pointers in your array to be const:

int main(){
  const char* names[4]= {
  "Dany", "Emily", "Eric", "Alex"};
}

This creates an array of four const char* (pointers to constant characters).

So each element of the array is a pointer to an array of chars.:

names[0]->"Dany"
names[1]->"Emily"
names[2]->"Eric"
names[3]->"Alex"

Hope that helps.

Galik
  • 47,303
  • 4
  • 80
  • 117
  • does this mean we are creating an array of char for each name (dany, emily...)? and then pointing each element of the pointer array to that particular array? – Fares Ismail Sep 13 '15 at 16:30
  • @FaresIsmail Each string literal (aka `"Danny"`) is a (constant) *character array* and the compiler will assign the *address* of its first element (`D`) to the relevant array element (`names[0]`). – Galik Sep 13 '15 at 16:34
  • @FaresIsmail Yes, what you are saying is correct. Each array element holds an *address* pointing to the first element of an array. – Galik Sep 13 '15 at 16:35