Good day, I need help ^__^
I have a void pointer: void *data;
I am told to "allocate len+1 characters and set the 'data' to the address of newly allocated memory setting the first character of 'data' to NULL (making the string blank)."
my guess is:
data = new char [len +1];
data[0] = 0;
Is my guess correct?
Thank you so much.
No, sorry, it is not correct. Most likely you want to work/play with C type of strings.
A C 'string' basically is just a sequence of bytes and the last byte contains the
value 0 (or \0 for an alternative notation). So a string "foo" takes four chars, f, o,
o and \0.
Your 'data' pointer is a void pointer now; better make that a char pointer instead
so you refer to all the chars in the sequence it refers to:
-
char* data= malloc(len+1);
-
data[0]= 0;
-
Those 'len+1' chars can contain a C string up to len+1 chars and the last byte
needs to be \0 char. Setting the first byte to \0 effectively 'constructs' an empty
C string.
You don't have to do that if you're sure that you're going to put a C string in that
area pointed by 'data'. The C string can contain 'len+1' chars including that trailing
\0 char.
For the memory allocation consistently choose either 'new' or 'malloc'. C just
uses 'malloc'; C++ prefers the 'new' operator.
kind regards,
Jos