Mcs
Mcs

Reputation: 564

switch strings without using any array notation in C

Hi I am kind of new to pointers and I am trying write a function that switches one string with another without using any array notation, so completely with pointers.

I have got this function, which works, but in this one, I use one array notation.

Is there an easier, better way to do this? Thank you.

void stringtausch(char *eins, char *zwei) {
    char first[50], *philfe = first, *one = eins, *two = zwei;
    while(*one != '\0') {
        *philfe++ = *one++;
    }
    *philfe = '\0';
    while(*two != '\0') {
        *eins++ = *two++;
    }
    *eins = '\0';
    philfe = first;
    while(*philfe != '\0') {
        *zwei++ = *philfe++;
    }
    *zwei = '\0';
}

Upvotes: 0

Views: 75

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

If both strings have equal length

void stringtausch(char *eins, char *zwei) {
    while ((*eins != '\0') && (*zwei != '\0')) {
        char swp;
        swp = *zwei;
        *zwei++ = *eins;
        *eins++ = swp;
    }
    *zwei = '\0';
    *eins = '\0';
}

if they don't it's not possible unless you allocate enough space before passing the pointers. And I don't see much benefit in that since you can

void stringtausch(char **eins, char **zwei) {
    char *swp;

    swp   = *zwei;
    *zwei = *eins;
    *eins = swp;
}

and call stringtausch

stringtausch(&s1, &s2);

Upvotes: 1

jake
jake

Reputation: 65

Well an easier way is to use strcpy, but if you want to do your way, it's much easier. A pointer points to the first cell address of an array or single cell. You can merely just do this:

char * eins = "dogslovecats";
char * zwei = "cats";

stringtausch(&eins, &zwei);

void stringtausch(char ** eins, char ** zwei) {

    char * temp;

    temp = *eins;

    *eins = *zwei;

    *zwei = *temp;
}

Upvotes: 0

Related Questions