In my C program I am trying to copy an array of char's to another array whilst removing the first element (element 0).
I have written:
char array1[9];
char array2[8];
int i, j;
for(i = 1, j = 0 ; i < 10, j < 9; i++, j++){
array2[j] = array1[i];
}
printf(array2);
When I print array2, it gives me a stack overflow.
Any ideas?
Use memcpy():
memcpy( array2, &array1[1], 8 );
Thats easier.
Two issues:
First, when printing a string with printf, and working with other standard C string functions in general, your char arrays need to be null-terminated so the functions know where the string ends. You are also writing one past the end of your arrays.
Second, when using printf, it is almost always a bad idea to use the string you want to print as the format string. Use
printf("%s", array2);
instead. If you use printf as in the original example and array2 can be influenced by the user, then your program is likely vulnerable to a format string vulnerability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With