function argument type

Dec 14, 2014 at 1:12pm
I am having a problem about function argument type. Please help me understand this.
Here is the definition of printOnNewLine():
1
2
3
4
 void printOnNewLine(char*x)
         { 
              cout << x << endl;
         }

 
printOnNewLine("hello");


I am wondering why printOnNewLine("hello") work.
Is "hello" considered as a pointer?
I think it is not. "hello" is a string and there is a pointer that points to the first character of that string (the character 'h').
Let's assume that the pointer is pS with the address value, say 0x000FE.
Then what will be printed on the screen, 0x000FE or the string "hello".
Last edited on Dec 14, 2014 at 1:25pm
Dec 14, 2014 at 1:42pm
My converter gives a warning: Deprecated conversion from string constant to 'char*'.

Dec 14, 2014 at 2:01pm
Thanks, I am reading this from an online lecture and it is really confusing.
Here is another example about the sum function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>
using namespace std;
 int sum(const int array[], const int length) 
{
long sum = 0;
 for(int i = 0; i < length; sum += array[i++]);
 return sum;
 }
 int main() 
{
 int arr[] = {1, 2, 3, 4, 5, 6, 7};
 cout << "Sum: " << sum(arr, 7) << endl;
 return 0;
}


Why not just write the sum function as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>
 using namespace std;
 int sum(const int*array, const int length) 
{
long sum = 0;
 for(int i = 0; i < length; sum += array[i++]);
 return sum;
 }
 int main() 
{
 int arr[] = {1, 2, 3, 4, 5, 6, 7};
 cout << "Sum: " << sum(arr, 7) << endl;
 return 0;
}



Dec 21, 2014 at 6:30am
Could anyone explain why?
"hello" is not a pointer here. Why can we put it into the function?
Dec 21, 2014 at 7:56am
"hello" is a pointer. In particular, it is a const char*. It is a pointer to the first char in memory where the characters 'h' 'e' 'l' 'l' 'o' '\0' are stored.
Dec 21, 2014 at 8:28am
Well, thanks! That surprises me!

I know the declaration below with str is a pointer to the first char in memory of "hello" but never thought that "hello" is also a pointer to the first char of the string!
 
char * str = "hello";
Topic archived. No new replies allowed.