I'm doing this exercise from a book on C programming, where I have to insert one character string into another.
first of all here is what I have written:
Code:
#include <stdio.h>
void insertString(char source[], char string[], int startNum)
{
int i = 0;
int j = startNum;
int k = 0;
while ( string[i] != '\0')
++i;
while ( source[j - 1] != '\0')
{
printf ("%s\n", source);
string[i] = source[j];
++i;
++j;
}
while ( string[k - 1] != '\0' )
{
source[startNum] = string[k];
++startNum;
++k;
}
}
int main (void)
{
int startNum;
char source[] = "the wrong son";
char string[] = "per";
void insertString (char source[], char string[], int startNum);
printf ("Enter the position in the source string where the string is to be inserted: ");
scanf ("%i", &startNum);
insertString (source, string, startNum);
printf ("%s\n", source);
return 0;
}
simple program, it seems, but it just doesn't work how I would expect it to. can't figure out why. I enter number 10 when it asks for the number and it returns "on" instead of "the wrong person".
I inserted the "printf" statement into the second "while" loop, to see what the "source" prints out and it is the "source" that seems to change even though it is only used to assign its element values to "string" and not other way round.
it is really p*****g me off now!
my brain seems to be fried because it doesn't make any more sense to me.
please explain why my code doesn't work even though there probably is another way to do this!