C++ strcpy non-constant expression as array bound -
I came back to C ++ after a long time in C #, PHP and other stuff and I have some strange things :
temp.name = new char [strlen (name) + strlen (r.name) + 1];
this compiled
temp.name = (char *) malloc (size (four [strlen (name) + strlen (r.name) + 1 ]));
it is not (temp.name is a char *)
compiler error
error C2540: non-array bindings Constant expression in form
Do anyone know what the problem can be and how it can be treated? Thank you
size (...)
expects a continuous compilation- time expression. strlen
is not a compile-time expression, it is a function that needs to be executed to get results. Therefore, the compiler is not able to reserve enough storage for the declared array as follows:
Four C [Stellen ("Hello")];
Although the length of the string is clearly 5, the compiler does not know.
To prevent this from getting worse, sizeof
here. Instead:
four * c = (four *) molk (strangle (name) + strannel +1);
This gives you an indication of n bytes in return. sizeof (char) == 1
is always correct, so the number of bytes in the buffer is equal to the size that you can store it. For a different type of malloc
array, multiply with the static size of an array element:
int * c = (int *) malloc (sizeof (int ) * 100);
This is okay, because sizeof
applies to a compiled time expression. Of course, the C ++ method is pretty clean:
< Code> int * c = new int [100];
Comments
Post a Comment