Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a pointer to a char array in C++

I'm relativly new to Coding and have some Problems understanding how pointers work in combination with arrays (whom on their own I i understand).

I understood that it's possible to create an array of pointers like:

#include <iostream>
using namespace std;

int main() {
    int i;
    int *pArr[10];
    pArr[0]=&i;
    return 0;
}

In a Tutorial I then found the following code:

#include <iostream>
using namespace std;

int main() {
    char *names[4] = {
        "name A",
        "name B",
        "name C",
        "name D"
};

for (int i = 0; i < 4; i++) {
    cout << names[i] << endl;
}
return 0;
}

Why is it, that I can assign Multiple chars, or to say a string, like "name A" to a pointer which should point to a char.

Shouldn't I A:

Only be able to assign the Address of a char to each of those 4 pointers I created.

And B:

Only be able to assign a pointer, to one single letter (a char), to each one.

I hope someone can help clear my confusion to some degree.

like image 951
questionsoverquestions Avatar asked Dec 11 '22 12:12

questionsoverquestions


2 Answers

This is a shortcut offered by the compiler to make it easier for programmers to include strings in their code.

When you write a string literal "name A", the compiler prepares a seven-character array for you:

const char hidden0[] = {110, 97, 109, 101, 32, 65, 0}; // "name A"

The first six numbers correspond to character codes of symbols in the string. The last character is zero - the so-called null terminator.

The compiler does the same for all four string literals, so your array initializer looks like this:

const char *names[4] = {
    &hidden0[0],
    &hidden1[0],
    &hidden2[0],
    &hidden3[0]
};

hiddenK is the array created for the corresponding string literal. It has no name, but the compiler knows its address, and places it in the name[] array.

like image 55
Sergey Kalinichenko Avatar answered Dec 13 '22 02:12

Sergey Kalinichenko


In C (and C++) a string literal (an expression such as "name A") has type const char*. Under the hood, these string characters are stored somewhere in data section in the binary. And the string literal is substituted with the pointer to the first of these characters. So, the following statement

char *names[4] = {
    "name A",
    "name B",
    "name C",
    "name D"
};

Instructs the compiler to allocate four strings in the data section, and then to assign four pointers to the pointer array names.

like image 39
Oleg Andriyanov Avatar answered Dec 13 '22 02:12

Oleg Andriyanov