5

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

6
  • 1
    Copy it to another array. Commented Mar 12, 2018 at 18:10
  • Can you use a temporary array? Or does it have to be done in-place using the original array? Commented Mar 12, 2018 at 18:12
  • Wow I cannot believe I didn't come up with that earlier! Thanks Commented Mar 12, 2018 at 18:12
  • I will copy it to another array and then write every letter the same but one step to the right Commented Mar 12, 2018 at 18:13
  • If you're stuck doing it in-place, move the "anana" over by copying from right-to-left (or just use memmove(), which does that for you). Commented Mar 12, 2018 at 18:20

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

3 Comments

Why can I not start from the end of the string and loop backwards making the last character take the value of the previous one and avoid using another array. I tried but the changes wouldn't reflect. Please take a moment to look through my code
You can't dynamically resize an array in C since the memory has to be contiguous. Hence the reason for two arrays in the above answer. As for your code I recommend you ask a specific question on SO.
Okay what if i dont care about the last character and just want to shift the remaining characters to the right and add a new character in the beginning. Then am I allowed to do it? Coz im not resizing the array but just altering the array's contents.
0

Please follow these steps:

  1. Create a new array of size 7 (Banana + terminator). You may do this dynamically by finding the size of the input string using strlen().
  2. Place your desired character say 'B' at newArray[0].
  3. Loop over i=1 -> 7
  4. Copy values as newArray[i] = oldArray[i-1];

1 Comment

Don't forget the terminator character! The string "Banana" is seven characters including it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.