Hello, I am trying to execute the following requirement. Note I try to use 'strcpy' but I am getting an error. I am not sure if this could be a problem with my compiler (onlinegdb.com) not recognizing 'strcpy'? I attempted to include library <stdio.h> but it was not accepted. This is C++. Error "strcpy not declared".
/*Exercise requirement:
Create a function that dynamically allocates memory for a string
with up to 256 characters using(use new keyword). Copy your name
into the string. Make sure there is no memory leak.
*/
#include <iostream>
#include <string>
void createstr() {
char * s = newchar[256];
strcpy(s, "myname");
delete s;
}
int main()
{
createstr();
return 0;
}
Note that if you're going to use c-style strings, to make one with enough space for 256 characters, you need it to be of size 257, because a c-string marks the end of the string with a zero.
Your function does do what's required, although it also seems a bit useless, since it destroys the string as well. Still, it does do what the exercise requirement said.