NO

Author Topic: Dynamicstring length determination  (Read 2566 times)

PhilG57

  • Guest
Dynamicstring length determination
« 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.
« Last Edit: July 30, 2012, 08:35:28 PM by Stefan Pendl »

CommonTater

  • Guest
Re: Dynamicstring length determination
« Reply #1 on: July 30, 2012, 01:26:33 AM »
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...
Code: [Select]
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:
Code: [Select]
#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.
 
« Last Edit: July 30, 2012, 02:11:15 AM by CommonTater »

PhilG57

  • Guest
Re: Dynamicstring length determination
« Reply #2 on: July 31, 2012, 04:09:04 AM »
Got it - strlen of the same character string.  Pretty cool, actually.  Thanks - again.

CommonTater

  • Guest
Re: Dynamicstring length determination
« Reply #3 on: July 31, 2012, 04:55:07 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.