Jack Burtenshaw
Jack Burtenshaw

Reputation: 15

Trying to increment a string pointer in C

Basically what I am trying to do is take a simple string like abcd and add it to a new string with asterisks in-between each letter like so, a*b*c*d. But it seems I am having issues with the function that is supposed to do this. Here is my code.

char widen_stars(char *user1p, char *user2p) {

    char *newStr;

    newStr = malloc(20 * sizeof(int));

    while (*user1p)  {
        *newStr = *user1p;
        //return printf("Test: %s \n", newStr);
        newStr++;
        //return printf("Test: %s \n", newStr);
        user1p++;
        *newStr = '*';
        newStr++;
    }

    return printf("String with asterisks: %s \n", newStr);
}

What I am trying to do is make a new string where I add in one letter from the original and then the asterisk right after, then increment and continue the cycle.

Where I am experiencing the problem is at the second return printf test it keeps on printing out nothing, but at the first return printf test it shows I've moved the first character over successfully, I'm not sure what's going on. New to programming so any help is appreciated.

Upvotes: 0

Views: 554

Answers (1)

pm100
pm100

Reputation: 50120

you need to keep the original newStr value. And zero terminate it too.

char widen_stars(char *user1p, char *user2p) {

char *newStr;
newStr = malloc(20 * sizeof(int));
char *keep = newstr;    // save start of new string
while (*user1p)  {
    *newStr = *user1p;
    //return printf("Test: %s \n", newStr);
    newStr++;
    //return printf("Test: %s \n", newStr);
    user1p++;
    *newStr = '*';
    newStr++;
}
*newstr  = '\0'; // zero terminate new string
return printf("String with asterisks: %s \n", keep); // print it
}

Upvotes: 1

Related Questions