TheSuds13
TheSuds13

Reputation: 347

Trying to swap strings in C?

I'm taking 2 character arrays as parameters and trying to swap those. This is what I have so far, but I'm getting the error "array initializer must be an initializer list". Can someone explain why this is happening and how to fix it?

Here's my code so far for the function:

void swapStrings(char string1[], char string2[])
{
    char tempString[] = string1;
}

Upvotes: 0

Views: 459

Answers (2)

abelenky
abelenky

Reputation: 64682

The first concern is to make sure that the two strings both have enough space to be swapped.

You can see the problem with trying to swap "Hello" with "ThisIsAVeryLongStringThatWillNotFitInTheSpaceOfHello"; there just isn't enough space in the first buffer to hold the second buffer.

Assuming there is enough space, you just need to swap every character, one-by-one until the entire strings are swapped.

void swapStrings(char string1[], char string2[])
{
    char temp;
    do
    {
        temp = *string1;
        *string1 = *string2;
        *string2 = temp;
    } while(*string1++ && *string2++);

    // At this point, the shorter string is done swapping.
    // But we need to finish swapping the longer string:

    if (*string1)
    {
        while (*string2++ = *string1++) ; 
    }
    if (*string2)
    {
        while (*string1++ = *string2++) ; 
    }
}

Note contrary to the answer by cdonts, no third buffer needs to be allocated or managed. The memory requirement is much smaller because there is only a single byte needed for swapping the strings.

Upvotes: 1

cdonts
cdonts

Reputation: 9599

In C you can't copy strings using the assignment operator, so you'll probably want something like this.

size_t length = strlen(string1) + 1;
char *tempString = malloc(length);
strncpy(tempString, string1, length);
free(tempString);

(Assuming both strings have enough space to be swapped as @abelenky said.)

Hope it helps!

Upvotes: 1

Related Questions