I have a char array filled with some characters. Let\'s say I have \"HelloWorld\" in my char array. (not string. taking up index of 0 to 9)
What I\'m trying to do is ins
The initial starting value for the inner loop is one short. It should be something like the following. Note too that since the characters are moved to the right, a new null terminator needs to be added:
ch[strlen(ch) + 1] = '\0';
for(j=strlen(ch); j>=i+2; j--) { // note no "-1" after the strlen
Edit As far as the "Is this a good way?" part, I think it is reasonable; it just depends on the intended purpose. A couple thoughts come to mind:
If you want to move all the characters up by one, then you could do it using memmove
.
#include <string.h>
char ch[15];
int make_room_at = 5;
int room_to_make = 1;
memmove(
ch + make_room_at + room_to_make,
ch + make_room_at,
15 - (make_room_at + room_to_make)
);
If you're going to manipulate a char array you shouldn't make it static. By doing this:
char ch[15];
you're hardcoding the array to always have 15 characters in it. Making it a pointer would be step 1:
char* ch;
This way you can modify it as need be.
Simply do:
#define SHIFT 1
char bla[32] = "HelloWorld"; // We reserve enough room for this example
char *ptr = bla + 5; // pointer to "World"
memmove(ptr + SHIFT, ptr, strlen(ptr) + 1); // +1 for the trailing null
You need to start the inner loop from strlen(ch) + 1
, not strlen(ch) - 1
, because you need to move the NULL-terminator to the right one place as well. Remember that strlen
returns the length of the string such that string[strlen(string)] == '\0'
; you can think of strlen
as a function for obtaining the index of the NULL-terminator of a C-string.