Reputation: 1568
I've got a String class. Recently, I found the poor thing couldn't handle:
String string = "Hello World";
I immediately decided to rectify this by adding a constructor. However, the exact parameter eludes me:
inline String(const char[] str) : Array(str, sizeof(str) / sizeof(char)) { }
generates the following error: "error C2146: syntax error : missing ')' before identifier 'str'"
What I'm thinking is that since it's a static char * literal, it isn't meant to be passed to a function. But, I don't actually know.
Thanks. (To reassure - Any array passed to Array will promptly be copied, not stored)
Upvotes: 1
Views: 162
Reputation: 19347
This particular error is generated because the square brackets []
should go after str
, not after char
. Change this and the error should disappear.
However, I don't think your calculation sizeof(str) / sizeof(char)
will work, because when an array is used as a parameter, you lose the information regarding the length of the string. It only work if you are using the original array. The calculation you perform will be equivalent to sizeof(char *) / sizeof(char)
, which will not reflect the size of the string. Instead, do as Asha says and use strlen
and strcpy
.
Upvotes: 0
Reputation: 1475
You not need to use sizeof(char) - according to standard of C++ sizeof(char) always equals 1.
Upvotes: 0
Reputation: 11232
Simplest would be to take const char*
as the parameter. Then use strlen
to find the string length, then allocate len+1
characters using new
and use strncpy
to copy the string to the newly allocated memory. BTW, any specific reason not to use std::string
?
Upvotes: 4