2

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.

16
  • Would you paste the output of your code, curious to see what your getting? Commented Apr 4, 2017 at 19:14
  • Getting nothing at all :/ Commented Apr 4, 2017 at 19:16
  • 2
    The question would be clearer if you tried to insert "Scampi" because we don't know which double "Chicken" is first. Commented Apr 4, 2017 at 19:22
  • 1
    You have nested for loops both using the same index variable. The outer loop looks useless to me Commented Apr 4, 2017 at 19:44
  • 1
    So the issue I can see is that, you aren't terminating s1copy with '\0' but you are calling length on it. The counting is most probably going out of bounds (that is an UB). Commented Apr 4, 2017 at 19:52

1 Answer 1

5

Not going to sugar coat it. This code is a mess. The task you're trying to accomplish is easiest if you simply

  • Copy from [0..min(n, lengthS1)) (note exclusivity of right side) from s1[] to your target.
  • Append s2[] to the target.
  • Append s1[min(n, lengthS1)] through s1[lengthS1] to the target.
  • Terminate the string
  • That's it.

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.

#include <stdio.h>

size_t length(const char s[])
{
    const char *end = s;
    while (*end)
        ++end;
    return end - s;
}

void insert(const char s1[], const char s2[], int n)
{
    size_t lengthOfS1 = length(s1);
    size_t lengthOfS2 = length(s2);
    size_t pos = (n < lengthOfS1) ? n : lengthOfS1;
    size_t i;

    // declare VLA for holding both strings + terminator
    char s1Copy[lengthOfS1 + lengthOfS2 + 1];

    // put in part/full s1, depending on length
    for (i=0; i<pos; ++i)
        s1Copy[i] = s1[i];

    // append s2
    for (i=0; i<lengthOfS2; ++i)
        s1Copy[pos+i] = s2[i];

    // finish s1 if needed.
    for (i=pos; i<lengthOfS1; ++i)
        s1Copy[i+lengthOfS2] = s1[i];

    // termiante string
    s1Copy[lengthOfS1 + lengthOfS2] = 0;

    puts(s1Copy);
}

int main()
{
    char ab[] = "Chicken and Chips";
    char  b[] = "Scampi";
    insert(ab, b, 0);
    insert(ab, b, 7);
    insert(ab, b, 100);
}

Output

ScampiChicken and Chips
ChickenScampi and Chips
Chicken and ChipsScampi

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.

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

6 Comments

Wow! Okay, now I see where I went wrong. It makes much more sense now since you broke it down into pieces, I think I'll opt for the pen and paper solution now. I'm a .NET and Java developer...and some other scripting languages etc... so I'm learning C still and it seems I'll start using pen and paper now - thank you for the well explained solution to the question!
@Imdad Glad it helped. I'd start with a pencil =P
Lucky you gave the solution and didn't try to debug OPs code. I tried that. Lesson learnt
@AjayBrahmakshatriya Oh, I tried. Believe me. Ultimately it was easier to just break down the problem trying to be solved , then show how it can be done, rather than broiling the many problems in the proposed solution.
@Imdad Prints the given null-terminated string to stdout, including a trailing newline. Effectively synonymous with printf("%s\n", s1Copy); but much easier to type. It is also highly likely much more efficient, as no argument format parsing has to be done. See it here. (and bookmark that site, it's stellar for C and C++ information).
|

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.