I am learning C and want to learn how I can copy the remaining characters leftover in the string after using strncpy. I would like to have the string Hello World broken down into two separate lines.
For example:
int main() {
char someString[13] = "Hello World!\n";
char temp[13];
//copy only the first 4 chars into string temp
strncpy(temp, someString, 4);
printf("%s\n", temp); //output: Hell
}
How do I copy the remaining characters (o World!\n) in a new line to print out?
First of all,
char someString[13], you don't have enough space for the stringHello World\n, since you have 13 characters but you need at least size of 14, one extra byte for theNULL byte,'\0'. You better off let the compiler decide the size of the array, wouldn't be prone to UB that way.To answer your question, you can just use
printf()to display the remaining part of the string, you only need to specify a pointer to the element you want to start at.In addition,
strncpy()doesn'tNULLterminatetmp, you are gonna have to do that manually if you want functions likeprintf()orputs()to function properly.