How to access elements of a const char*

closed account (Ey80oG1T)
I have this code:

1
2
3
4
void GetLetter(const char* inputString)
{
    cout << "The 1st letter is " << inputString[0];
}


How do I do something like that? Or more specifically, how do I access characters in a const char*?
Your code is correct.

const char* is a pointer to an array of chars, or a pointer to a char where the thing pointed to is const.

The first element is inputString[0].
The second element is inputString[1].
and so on.

The reason why it may point to a single char or the start of an array is an accident in C that we all have to live with. There is a reason but it's beyond the scope of the question.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

char GetLetterByIndex(const char *inputString, int index)
{
    return inputString[index];
}

int main()
{
    char str[] = "Hello";
    std::cout << GetLetterByIndex(str, 4) << std::endl;     // prints 'o'
}
Last edited on
Topic archived. No new replies allowed.