-
2 dimension string array
how can i insert a character on a 2 dimension string array
for example if i have to insert "d" on check[0][5].. i have tried the following way but after inserting 5 on check[0][5] it deletes all the elements which are after that index no.. please help me
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main(void)
{
char check[1][80]={"............................................... ..............................."};
clrscr();
printf("%s\n",&check[0]);
strcpy(&check[0][5],"d");
printf("%s",&check[0]);
getch();
}
-
You can't just insert a character into the array, you need to move all the remaining characters up by one as well.
-
a small example will really help me .. can you please show me an example
-
A "small" example would probably end up being the complete function, so here's some pointers instead:
Your function prototype might look like this:
>>insert (char *s, int InsertOffSet, char c)
and you'd call it like so:
>>insert (check[0], 4, 'd');
Now within the function, you need to store away the existing character at offset 4 into a temp variable, then you can replace it with the new character.
Then, store away the next character in the string, and then replace it in the string with the stored value from above.
Follow the same principle until you reach the end of the string, where you then add a new trailing \0.
Draw it out on paper if you get stuck.
From your code you've already posted:
>>printf("%s\n",&check[0]);
This should be
>>printf("%s\n",check[0]);
>>void main(void)
Read this
-
The other thought is that if you mean by "insert" you simply want to replace whatever is in check[0][5] is to be overwritten by 'd' then the command is simply
check[0][5] = 'd';
What you did with strcpy(&check[0][5],"d");
is replace the 'string' starting at position 0,5 with the string "d". In other words,
check[0][5] = 'd';
check[0][6] = '\0';
which effectively truncates the string you had in check[0]
Walt