Reputation: 345
I got the char array "anana" and I am trying to get a "B" into the beginning in the char array so it spells "Banana" but I cannot wrap my head around how to construct a simple while loop to insert the B and then move every letter one step to the right
Upvotes: 4
Views: 21602
Reputation: 564
Please follow these steps:
strlen()
.newArray[0]
.i=1 -> 7
newArray[i] = oldArray[i-1];
Upvotes: 0
Reputation: 5037
You can use a more traditional approach using...
#include <stdio.h>
int main()
{
char s[] = "ananas";
char b[7] = "B";
for(int i = 0; i < 7; ) {
char temp = s[i++];
b[i] = temp;
}
printf("%s", b);
return 0;
}
Upvotes: 1
Reputation: 70392
Assuming:
char array[7] = "anana";
Then:
memmove(array+1, array, 6);
array[0] = 'B';
The memmove
function is specifically for cases where the data movement involves an overlap.
Upvotes: 7