Pointer As An Argument for A String

Hello!

Why do you pass a pointer through a function when you want to pass a string?

Like this :

1
2
3
4
5
6
7
8
9
void PrntStr(char *str)
{
  std::cout << str << endl;
}

void main(){
PrntStr("Hello!");
}

And this prints "Hello!".

So, my question again is, why a string is passed through a pointer (what does *str point at?) and since that it is stored in *str, why when you print it you print the variable not the pointer, and the pointer (e.g cout << *str;) gives you an "H".

Thanks,
Last edited on
A C string is an array of chars.
cout knows that so when you are passing to the << operator a pointer to char, it will print it as a null terminated C string
http://www.cplusplus.com/doc/tutorial/ntcs/
Thanks,

Well I know that already, but how could the whole string is passed in *str, and str prints it (why not *str?). Since *str would point to the first index of the array, why do you pass the string "Hello!" to a pointer at the first place?

Wouldn't str be the address of the first index?
Last edited on
A quoted string ("Hello") ha a type of const char*, which is a character pointer pointing to the first element of the string. Read the article Bazzy posted.
how could the whole string is passed in *str
because when you pass an array to a function, you are actually passing a pointer to the first index of the array. in this case "Hello!" is actually an array of chars.

and str prints it (why not *str?).
because *str is actually equal to *str[0] with a value of 'H' and output streams treats char* in special way, printing the values of the pointer terminated by a null character '\0' instead of the address the pointer it is pointing to

Since *str would point to the first index of the array, why do you pass the string "Hello!" to a pointer at the first place?
because pointer can be use to point other variables..
Last edited on
Thanks all guys, it's all comprehended now. Thanks for your efforts.
Topic archived. No new replies allowed.