Length Function:
int length(const char s[])
{
int length = 0;
while(s[length]!='\0')
{
length++;
}
return length;
}
Insert Function:
void insert(char s1[], const char s2[], int n)
{
char *beginOfString = s1;
int lengthOfS1 = length(s1);
int lengthOfS2 = length(s2);
char s1Copy[lengthOfS1 + lengthOfS2];
int c, afterC, lengthOfRemainingPart;
c = 0;
c = n + 1;
beginOfString += c;
afterC = c; //nth position to start from to add onto array
lengthOfRemainingPart = length(beginOfString);
c = 0;
int counter = 0;
for(c = 0; c < length(s1) - 1; c++) {
s1Copy[c] = s2[counter];
for(c = afterC; c < (lengthOfS1 + lengthOfS2) - 1; c++) {
if(c == afterC) {
s1Copy[c] = s2[counter];
} else {
counter++;
if(s2[counter] != *"\0")
s1Copy[c] = s2[counter];
}
}
}
c = 0;
for(c = 0; c < length(s1Copy) - 1; c++) {
printf("\n %c \n", s1Copy[c]);
}
printf("\n");
printf("\n %s \n", beginOfString);
printf("\n %s \n", "LINE");
}
Function Call (and related declarations):
#define MAX_STR 20
char ab[MAX_STR + 1] = "Chicken and Chips";
char b[MAX_STR + 1] = "Scampi";
insert(ab, b, 7);
I'm trying to insert a char array into another char array whilst keeping the rest of the chars still within the array but shifted along depending on where the user wants to insert the char array according to the n value.
This doesn't seem to be working and seems to output the wrong values. The function calls and the function header (parameter types, etc.) needs to stay how I've put them. Only the function body itself can change.
The output should be "ChickenScampi and Chips"
Any ideas where I am going wrong? Cheers.
Not going to sugar coat it. This code is a mess. The task you're trying to accomplish is easiest if you simply
s1[]
to your target.s2[]
to the target.s1[min(n, lengthS1)]
throughs1[lengthS1]
to the target.And above all, the target must be able to accommodate both strings and a nulchar terminator, which your target buffer does not do (it is short by one character).
There is no need for nested for-loops. And yours is broken regardless as it is walking on its own indexing variables.
Output
Summary
If you're not sure what is going on, the last thing you should be doing is writing more code. Rather, stop coding, get some paper and a writing instrument, and rethink the problem.