I know the starting address of the string(e.g., char* buf
) and the max length int l;
of the string(i.e., total number of characters is less than or equal to l
).
What is the simplest way to get the value of the string
from the specified memory segment? In other words, how to implement string retrieveString(char* buf, int l);
.
EDIT: The memory is reserved for writing and reading string of variable length. In other words, int l;
indicates the size of the memory and not the length of the string.
Use the string's constructor
EDIT:
OK, then if the C string length is not given explicitly, use the ctor:
string& assign (const char* s); => signature FYR
Reference/s here.
Or, if the string already exists:
Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to
length
characters, or until a null terminator, whichever comes first, then you can use this:There seems to be a few details left out of your explanation, but I will do my best...
If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.
If the above is not the case, I'm not sure how you determine where a string ends.