I turned back to C++ after a long time in C#, PHP and other stuff and I found something strange:
temp.name = new char[strlen(name) + strlen(r.name) + 1];
this compiles
temp.name = (char *)malloc(sizeof(char[strlen(name)
+ strlen(r.name) + 1]));
this doesn’t (temp.name is a char *)
The compiler error is
error C2540: non-constant expression
as array bound
Does anyone know what the problem might be and how it might be remedied? Thank you.
sizeof(...)expects a constant compile-time expression.strlenis not a compile-time expression, it is a function which needs to be executed to get a result. Therefore, the compiler is not able to reserve sufficient storage for an array declared like this:Although the length of the string is clearly 5, the compiler does not know.
To avoid this pitfall, do not use
sizeofhere. Instead:This gives you a pointer to n bytes in return.
sizeof(char)==1is always true, so the number of bytes in the buffer equals the number of chars you can store in it. Tomallocarrays of a different type, multiply with the static size of one array element:This is Ok, because
sizeofis applied to a compile-time expression. Of course, the C++ way is much cleaner: