Reputation: 77
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?
Upvotes: 3
Views: 4587
Reputation: 3990
It's not necessary to use an extra array2 like
printf("%.8s",array1+1);
Upvotes: 1
Reputation: 138357
Your string isn't null-terminated, so when its printed it continues printing characters past the 8 you've allocated looking for one but runs out of stack space before then. You're also writing to one character more than you've allocated and your conditions should be "combined" with &&
-- a ,
ignores the result of the first expression. You should also avoid using a string variable as the string formatter to printf
.
Here's your code fixed:
char array1[10] = "123456789";
char array2[9];
int i, j;
for(i = 1, j = 0 ; i < 10 && j < 9; i++, j++){
array2[j] = array1[i];
}
printf("%s\n", array2);
You can also simplify the loop by using a single index variable i
and indexing array2
with i+
. You can also remove the loop entirely by using strncpy
, but be aware that if n
is less than the length of the string + 1 it won't add a null-terminator.
Upvotes: 2
Reputation: 22979
Just use strcpy()
(if they're both strings!) strcpy()
wants a pointer to the source and a pointer to the destination. If you want to skip the first element of the source array just pass source + 1
:
char source[] = "ffoo";
char dest[] = "barbar";
strcpy(dest, source + 1);
// now dest is "foo" (since the ending \0 is copied too)
printf("\n%s\n", dest);
Upvotes: 0
Reputation: 4879
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.
Upvotes: 3
Reputation: 9820
To further expand on marcog's answer: you are declaring array1 with 9 elements, 0-8, and then writing from 0-9 (10 elements). Same thing with array2.
Upvotes: 0
Reputation: 94
When you say printf(array2)
, it thinks it's printing a null-terminated string. Since there is (possibly) no \0
in array2
, printf
continues on past the end of array2
, wandering into memory it isn't supposed to.
Upvotes: 1