Hello, I have a void pointer 'data' which I used to cast to a string later on by a method that sends in another data
Im using
How do I make sure that this->((char*)data) is null terminated?Code:strncpy((char*)this->data,data,len);
Hello, I have a void pointer 'data' which I used to cast to a string later on by a method that sends in another data
Im using
How do I make sure that this->((char*)data) is null terminated?Code:strncpy((char*)this->data,data,len);
edit: Nope, won't work. strlen() only works on null terminated strings.Code:if(data[strlen(data)] == '\0') cout<<"yes"<<endl;
Last edited by 7stud; 11-28-2005 at 08:22 AM.
What I meant was, how do I null terminate it?
strcpy((char*)data,'\0'); ?
Isnt that deprecated?
strcpy() only works with null terminated strings, too--that's how strcpy finds the end of the first string.
I don't think you can unless you know the size of the array. With any C++ array, you have to pass the size around with it--otherwise you'll go out of bounds.
Last edited by 7stud; 11-28-2005 at 08:29 AM.
So what do I do when my assignment says
IOLabel &operator=(const char *data); copies the maximum of "len" character from the incoming argument "data" into the data attribute of the class. Make sure that the data is null terminated.
strncpy's destination string will be 0-terminated as long as the source-string is shorter then the specified nr of characters.
To be shure that it is alwais 0-terminated you could just
KurtCode:((char*)this->data)[len-1]='\0';
It's ambiguous, but this sentence:
is probably referring to the data member of the class. Typically, you'll use 'new' to create the memory for your member variable to store len + 1 characters. Then you copy each character from the source string into your member variable string, and finally for the last index position of your member variable string, you assign it a '\0' character.Make sure that the data is null terminated.
Last edited by 7stud; 11-28-2005 at 08:45 AM.
Aside from the syntax error (strcpy expects two pointers to characters, not a pointer and a char) this will cause the first character of data to be the null character, thus emptying the string. The syntax error can be fixed by doing:Originally Posted by INFERNO2KCode:strcpy((char*)data, "");It only matters that the source is null terminated. You are probably thinking of strcat() which appends the source onto the destination.Originally Posted by 7stud