1

I saw this example:

const char* SayHi() { return "Hi"; }

And it works fine, but if I try to remove the pointer it doesn't work and I can't figure out why.

const char SayHi() { return "Hi"; } \\Pointer removed

It works if I assign it a single character like this:

const char SayHi() { return 'H'; } \\Pointer removed and only 1 character

But I don't know what makes it work exactly. Why would a pointer be able to hold more than one character? Isn't a pointer just a variable that points to another one? What does this point to?

Metsuryu
  • 35
  • 1
  • 8
  • Did you notice this scary warning? __warning: return makes integer from pointer without a cast__ – Bill Lynch Sep 16 '14 at 22:31
  • 1
    Oh boy, it's really basic stuff... try to find tutorial/books about C++. In this case, think about pointer to char as an array of chars. – Kenan Zahirovic Sep 16 '14 at 22:32
  • @sharth I don't understand that. return makes integer from pointer without a cast. It's confusing sorry. char is an integer right? return makes it without a cast? Isn't a cast a way to convert a type of variable to another? What is its use here? – Metsuryu Sep 16 '14 at 22:47
  • @KenanZahirovic Yes I'm just starting. I'm reading [this](www.learncpp.com/) but I got confused and figured to ask here. I tought that it may be like an array, but is it a rule or is there something I'm missing? Does it work for every variable type? I tought pointers just pointed to the address of another variable, why would it make the char an array? – Metsuryu Sep 16 '14 at 22:47

2 Answers2

3

That is because a char is by definition a single character (like in your 3rd case). If you want a string, you can either use a array of chars which decays to const char* (like in your first case) or, the C++ way, use std::string.

Here you can read more about the "array decaying to pointer" thing.

Community
  • 1
  • 1
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • @Metsuryu [An array is not a pointer!](http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c) Arrays just decay to pointers. (It's a C-answer, applies to C++ too.) Btw you can make code highlight by putting it between '`' . – Baum mit Augen Sep 16 '14 at 23:15
1

You are correct that a pointer is just a variable that points somewhere -- in this case it points to a string of characters somewhere in memory. By convention, strings (arrays of char) end with a null character (0), so operations like strlen can terminate safely without overflowing a buffer.

As for where that particular pointer (in your first example) points to, it is pointing to the string literal "Hi" (with a null terminator at the end added by the compiler). That location is platform-dependent and is answered here.

It is also better practice to use std::string in C++ than plain C arrays of characters.

Zach
  • 7,730
  • 3
  • 21
  • 26