>i'm probably doing something basically wrong in the fubction maybe.
Are you passing any arguments to your program? If not, argv[1] isn't guaranteed to be there, and if it is, it's pretty much sure to be NULL. If you're passing something, make sure that it's less than 30 characters or you'll overflow the buffer. strncpy is the logical choice, but it's really poorly named and doesn't do quite what you're expecting. I'd say use strncat instead:
#include <string.h>
int main ( int argc, char *argv[] )
{
char buffer[30];
if ( argc > 1 ) {
/* strncat won't work if buffer isn't already a string */
buffer[0] = '\0';
strncat ( buffer, argv[1], 29 );
}
return 0;
}
>It will try to copy n characters whether it hits an
>architecture-dependent read boundary or not.
An architecture-dependent read boundary? Can you describe what you mean by this?
>Use strncpy(). It is fully standard and stops in the right place.
memcpy is fully standard. Also, strncpy
always copies n characters. If the string isn't shorter than the buffer, strncpy will pad the buffer all the way to the count with null characters. If the string is longer than the buffer, strncpy will
fail to null terminate the buffer. Despite the name, strncpy shouldn't be used as a "count restricted strcpy".
>To convert a string to an integer #include <cstdlib> and use the atoi() function
I wouldn't recommend atoi unless you've completely validated the input string first. It's basically impossible to tell if atoi failed without prior validation, and if the string isn't representable as an integer then calling atoi produces undefined behavior. It's too risky, so you should use strtol instead:
char *end;
long temp;
int x;
errno = 0;
temp = strtol ( buffer, &end, 0 );
if ( end == buffer )
puts ( "No conversion made" );
else if ( *end != '\0' )
puts ( "Partially invalid string" );
else if ( temp < INT_MIN || temp > INT_MAX )
puts ( "Out of range value" );
else
x = (int)temp;