C++ - pointer function parameter
I asked a question here: C++ - class issue
What I'm still not getting is the pointer parameter here:
void setInfo(char *strName,int id,double wage)
Where it is called by:
abder.setInfo("Abder-Rahman",123,400);
I know that the name of the array is a pointer. But, why should we have to have a pointer data type? Cannot we use a char[]
in the function parameter list? As I think I got an error when I tried that.
T开发者_高级运维hanks.
But, why should we have to have a pointer data type?
Because the size of the arguments to the function needs to be known when the function is compiled. I.e. the function needs to know how far up the list of arguments in memory to find id
and wage
.
Cannot we use a char[] in the function parameter list?
Yes you can, but it is still passed by pointer. None of the additional attributes the data has as part of being an array (such as sizeof()
returning the total size of the array) are preserved inside the called function. The ability to use []
in the function signature is just an indicator for you that the item passed should be an array of some type (rather than a pointer to, say, a structure).
For reference, from the C++03 standard, § 8.3.5 3:
After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively.
Furthermore, an array declared with []
is an incomplete object type (§ 8.3.4 1), though this shouldn't cause a problem when declaring a function parameter as it will be converted to a pointer.
char[] is also a pointer. And yes, you could use it.
An array and a pointer are very much related - you can even use a pointer like an array, like
void foo(char *ptr) {
ptr[2] = 'x';
}
In your case, you get a compilation error (or warning) because string literals (like "foo"
) are considered const, i.e. they may not be modified, and since a function that doesn't take a const pointer doesn't make a promise not to change it, the compiler refuses to hand it a string literal.
You'd need to do
void setInfo(const char *strName,int id,double wage)
In general, you should always use const
for pointer and reference arguments unless you're planning to modify the object.
精彩评论