开发者

Question about C++ character pointer

I'm still very new to C++ and I'm very confused about something that looks like this:

int main()
    {
     开发者_开发知识库    char* aCharPointer = "A bunch of characters";
         return 0;
    }

Why can you do that with a character pointer? Perhaps there is another place with the answer but I don't know where to look or what I'm looking for. Thanks for your time.


This has to do with strings in C (and make no mistake, that IS a C string). Strings are an array of characters. The following code:

char* txt = "Hello";

Produces the following character array:

H|e|l|l|o|\0

And txt points to the first element. The last element is a null terminator, and it's how anything using the string knows that the string has ended.

As a side note, pointers in C and C++ can either point to a single item, or an array of items of the same type. There's no way by just looking at it to know which it is, however by convention if you see a char* odds are pretty good it's a string.

Thus it has been, thus shall it always be. Amen.

If you're wondering how to make a C++ string, use the std::string class.


This is a C-style string, which means that it's really an array of characters with a null (ASCII code 0) character at the end of the string to indicate that it's the end (the compiler puts it in for you when it sees the literal).

The character pointer points to the first character in the array (this is because arrays decay into pointers whenever the context demands it).

Pointers can have the p[i] subscript syntax applied to them, which is identical to saying *(p + i). This is a common idiom for accessing the ith element of an array given a pointer to the first element.

Using these facts, you can iterate through all the characters in the array this way:

// '\0' is the null character
for (int i = 0; aCharPointer[i] != '\0'; ++i) {
    // Do something with aCharPointer[i]
}

or this way:

for (char *p = aCharPointer; *p != '\0'; ++p) {
    // Do something with *p
}

You can also call a function that requires a character pointer to a C-style string:

#include <cstring>
size_t lengthOfString = strlen(aCharPointer);

You can, of course, also manually dereference the pointer:

assert(*aCharPointer == 'A');


What You Can Do ?

"A bunch of characters" is a string literal. A string literal is statically allocated in constant section of your program. The effect of char *p = "LITERAL"; is to create a pointer on stack to point to that string literal.

Question about C++ character pointer

Since p is pointing to a constant, the original definition would have been const char *p = "LITERAL"; However, to be backward compatible with lots of existing C code, it's ok with previous form of definition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜