Tcranmer
Tcranmer

Reputation: 29

Passing an Asterisk into a string in c

I have a question about putting a * into a concatenated string and having it print out the asterisk. My code takes 2 parameter strings, and needs to return a pointer that is the First string and Second string concatenated BUT I need it to have * inbetween each character. (Ex: String 1: 09876; String 2; 12345 result; 0*9*8*7*6*1*2*3*4*5); My issue isn't with trying to print this result, it's adding the asterisk, especially since C won't let me just declare a * or have a pointer point to *. So I'm a bit stuck. Here's my code

   char* widen_stars(char * str1, char *str2)
{       
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(strlen(str1) + strlen(str2)+ 29);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    char *asterix;
    *asterix = '*'; //Pointer pointing to *, won't let me though//
        while(*p1 != '\0'){
        *p3 = *p1;
        p1++;
        p3++;
        *p3 = *asterix; // Needs to add an *, after printing the first element.//
        }
        while(*p2 != '\0'){
        *p3 = *p2;
        p2++;
        p3++;
        *p3 = *asterix;
        }
    return str4;
}

I supplied just my function, because this is the only part of my code I get problems. EDIT: The 29 in my Malloc is to keep account of asterisks and the NULL character (The parameter strings have a maximum of 30 characters) I fixed my problem of adding the asterisk thanks to the community, now I get a segmentation fault, this should be fun.

Upvotes: 1

Views: 1961

Answers (1)

Barmar
Barmar

Reputation: 781028

asterix doesn't need to be a pointer, it's just a single character.

You're not using the correct size when allocating the result string. It needs to have 2 characters for each character in the two original strings -- 1 for each of the characters you're copying, and 1 for the asterisks in between.

You need to add a null terminator to the final result. This can replace the final asterisk, since you're only supposed to have asterisks between the characters, not after each character.

char* widen_stars(char * str1, char *str2)
{       
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(2 * ls1 + 2 * ls2);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    const char asterix = '*';
    while(*p1 != '\0'){
        *p3++ = *p1++;
        *p3++ = asterix; // Needs to add an *, after printing the first element.//
    }
    while(*p2 != '\0'){
        *p3++ = *p2++;
        *p3++ = asterix;
    }
    // Replace last asterisk with null byte
    if (p3 > str4) {
        p3--;
    }
    *p3 = '\0';
    return str4;
}

Upvotes: 1

Related Questions