简体   繁体   中英

Creating string concatenation function in C

This is a hw assignment that I am having a lot of difficulty with. I'm tasked with creating my own function that accepts two strings and will concatenate the two strings together and will return a character pointer to the new string. This is what I currently have:

char * my_strcat(char p[], char t[]) {
    printf("Made it into my_strcat.\n");

    int size1;
    int size2;

    size1 = my_strlen(p);
    size2 = my_strlen(t);

    int size3;
    size3 = size1 + size2 +1;

    printf("This many characters allocated for in memory: %i\n", size3);

    char* MemLoc = (char *)malloc(sizeof(char)*(size1+size2+1));
    char* BookMark = MemLoc;

    printf("Address of MemLoc: %p\n", MemLoc);
    printf("Address of BookMark: %p\n", BookMark);

    int count = 0;

    while(count < size1) {
        *BookMark = p[count];
        printf("Address of MemLoc: %p\n", MemLoc);
        printf("Latest char: %c\n", *MemLoc);
        count++;
        BookMark++;
        printf("Address of MemLoc: %p\n", MemLoc);
    }

    count = 0;

    while(count < size2) {
        *BookMark = t[count];
        printf("Latest char: %c\n", *MemLoc);
        count++;
        BookMark++;
    }

    *BookMark = '\0';
    printf("Concatenated string: %s\n", MemLoc);

    return MemLoc;
}

I have a lot of print statements in there trying to determine my error but I still can't pin it down. Depending on what type I print as, I am getting "nil", "null", and nothing for the last print statement. The last print statement (in my opinion) should be printing the final concatenated string.

Also, I had to construct the my_strlen method to calculate string length. This is working correctly and returns the correct length values of the strings sent in. Any suggestions for fixing this method?

You might use a printf of the form

    printf("built string is '%.*s'\n",size3,MemLoc);

or

    printf("build string is '%.10s'\n",MemLoc);

to help you debug. By using the precision limit on the %s format specifier you can prevent the format conversion from running off of the end of the unterminated partially built string. Since its just debug and you probably know the length of your test case there is really no harm in using the fixed length version.

For help in this debugging you would probably also want to

    memset(MemLoc,'#',size3);

after you malloc it and before you start construction. This can help avoid confusion with garbage that was already in memory vs. what you are doing to it.

With that initialization and scattering the prints around, I'm hopeful you will be able to debug your problems.

I agree with friz's comment that the +4 for stepping through the string doesn't make sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM