0

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';
}
1
  • 1
    It depends on what you are trying to do, in your code if the strings are not of equal lengths you will have undefined behavior trying to write past the shortest. Commented Jan 4, 2015 at 19:03

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Downvote? why? can you explain what is wrong? may be I don't know that, may be I just missed it...
0

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;
}

1 Comment

To be picky, first define the function and then call it. Just to avoid that one who read this will try to compile it and we will ruin his day ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.