How do I determine the length of an "embedded" character string? I would like to code a strncpy in which the length field (??? in the example below) would be determined during compilation. Is there some way to reference the "...." characters with a 'sizeof' or 'strlen' call so I can get its length?
strncpy(ToLocation, "some characters here", ???);
Thanks.
Quote from: PhilG57 on July 29, 2012, 10:24:00 PM
How do I determine the length of an "embedded" character string? I would like to code a strncpy in which the length field ( ??? in the example below) would be determined during compilation. Is there some way to reference the "...." characters with a 'sizeof' or 'strlen' call so I can get its length?
strncpy(ToLocation, "some characters here", ??? );
Thanks.
Like this...
strncpy(To, "This is a test!",strlen("This is a test!");
However; strncpy() isn't needed with string constants so long as you know the buffer is big enough, since they're guaranteed to be 0 terminated.
If you're copying to a buffer that may be smaller than your text, use the buffer's size in strncpy()
For example:
#define BUF_SIZE 16;
// in active code
char buf[BUF_SIZE + 1] = {0}; //extra character for trailing 0;
strncpy(buf, "This is going to be longer than the buffer",BUF_SIZE);
This avoids buffer overflow problems but will completely copy shorter strings.
Got it - strlen of the same character string. Pretty cool, actually. Thanks - again.
Quote from: PhilG57 on July 31, 2012, 04:09:04 AM
Got it - strlen of the same character string. Pretty cool, actually. Thanks - again.
The most appopriate use is the second one where you use the size of the text buffer itself.
Glad to help.