3

I have to admit, i have no idea how to use pointers, but I tried non the less. the problem with my program is that it shows the string in reverse, except for what was the first letter being missing and the entire string is moved one space forward with the first element being blank. for example it show " olle" when typing "hello".

#include <iostream>
#include <string>

using namespace std;

string reverse(string word);

int main()
{
char Cstring[50];
cout<<"enter a word: ";
cin>>Cstring;
string results = reverse(Cstring);
cout <<results;
}

string reverse(string word)
{
    char *front;
    char *rear;
    for (int i=0;i< (word.length()/2);i++)
    {
            front[0]=word[i];
            rear[0]=word[word.length()-i];
            word[i]=*rear;
            word[word.length()-i]=*front;
    }
    return word;
}

The new code works perfectly. changed the strings to cstrings. the question technicaly asked for cstrings but i find strings easier so i work with strings then make the necesary changes to make it c string. figured out ho to initialize the rear and front as well.

#include <iostream>
#include <cstring>

using namespace std;

string reverse(char word[20]);

int main()
{
char Cstring[20];
cout<<"enter a word: ";
cin>>Cstring;
string results = reverse(Cstring);
cout <<results;
}

string reverse(char word[20])
{
    char a='a';
    char b='b';
    char *front=&a;
    char *rear=&b;
    for (int i=0;i< (strlen(word)/2);i++)
    {
            front[0]=word[i];
            rear[0]=word[strlen(word)-1-i];
            word[i]=*rear;
            word[strlen(word)-1-i]=*front;
    }
    return word;
}
10
  • 1
    I have a feeling that your code works by sheer luck. You're using (dereferencing) two char pointers that you haven't initialized, front and rear. Commented Jun 19, 2013 at 20:06
  • 2
    You haven't allocated memory for front and rear, so you're invoking undefined behaviour when using front[0] and rear[0]. Apart from that, the last index of the word is word[word.length() - 1] and you should use word[word.length() - 1 - i]. Commented Jun 19, 2013 at 20:06
  • so what do i initialize them to, any old character or something specific, as I have said I am quite new to pointers. Commented Jun 19, 2013 at 20:08
  • "i have no idea how to use pointers" — good, this here planet needs less pointers and more sane, human-readable code. Please help the world stamp out pointers by refusing to learn them. Commented Jun 19, 2013 at 20:09
  • ok. i see, i think. so basicly i am trying t access a non existant element in word. Commented Jun 19, 2013 at 20:10

4 Answers 4

5
char *front;
char *rear;

then later

front[0]=word[i];
rear[0]=word[strlen(word)-1-i];

Not good. Dereferencing uninitialized pointers invokes undefined behavior.

Apart from that, your code is overly complicated, it calls strlen() during each iteration (and even multiple times), which is superfluous, and the swap logic is also unnecessarily complex. Try using two pointers instead and your code will be much cleaner:

void rev_string(char *str)
{
    char *p = str, *s = str + strlen(str) - 1;
    while (p < s) {
        char tmp = *p;
        *p++ = *s;
        *s-- = tmp;
    }
}

The thing is, however, that in C++ there's rarely a good reason for using raw pointers. How about using std::reverse() instead?

string s = "foobar";
std::reverse(s.begin(), s.end());
Sign up to request clarification or add additional context in comments.

2 Comments

Yay for the correct short C-style code. The uninitialized front and rear were fixed in the second edition in the question, but that is ... interesting code, shall we say. And the misuse of strlen() is pretty blatant too.
@JonathanLeffler Thanks. Yap, and I didn't even want to mention the unreadable spaceless coding style, which is not strictly a technical error, but still makes code look very unprofessional.
1
inline void swap(char* a, char* b)
{
    char tmp = *a;
    *a = *b;
    *b = tmp;
}

inline void reverse_string(char* pstart, char* pend)
{
    while(pstart < pend)
    {
        swap(pstart++, pend--);
    }

}

int main()
{
    char pstring[] = "asfasd Lucy Beverman";
    auto pstart = std::begin(pstring);
    auto pend = std::end(pstring);
    pend -= 2; // end points 1 past the null character, so have to go back 2
    std::cout << pstring << std::endl;        
    reverse_string(pstart, pend);
    std::cout << pstring << std::endl;
    return 0;
}

Comments

0

you can also do it like this:

#include <iostream>
#include <cstring>

using namespace std;

string reverse(char word[20]);

int main()
{
char Cstring[20];
cout<<"enter a word: ";
cin>>Cstring;
string results = reverse(Cstring);
cout <<results;
}

string reverse(char word[20])
{
    char a='a';
    char b='b';
    char *front=&a; 
    char *rear=&b;
    for (int i=0;i< (strlen(word)/2);i++)
    {
            *front=word[i];
            *rear=word[strlen(word)-1-i];
            word[i]=*rear;
            word[strlen(word)-1-i]=*front;
    }
    return word;
}

it successfully works on my system ,i.e. on emacs+gcc on windows 7

2 Comments

As far as I can see from the edit records, user2420395 created his answer (in an edit to the question) on 2013-06-19 20:57; you created your answer on 2013-06-20 05:10, some 8 hours later. The only difference between what he wrote and what you wrote is front[0] vs *front and rear[0] vs *rear. This does not change the function of the code; only the nomenclature is different. I'm not sure why you'd expect any credit for it, therefore. It isn't even a very good algorithm. There are far too many uses of strlen() to be sensible. The best solution using C pointers is far simpler.
It means that i may not have seen the edit at that time or i could not have paid attention to it, at that time there were important problems as you can see, OP had not initialized front and rear variables at that time,and as you can see mine was the only answer so i thought accepting it won't do any harm but now other "better" answer is available , i won't expect any credit whatsoever.It can't be undermined that new users here crave for "reputation" so that was my cause.If you feel mine is not very good answer,you are good enough to down vote it!
-1

Taken from C How To Program Deitel & Deitel 8th edition:

void reverse(const char * const sPtr)
{
    if (sPtr[0] == '\0')
        return;
    else
        reverse(&sPtr[1]);
        putchar(sPtr[0]);
}

1 Comment

Ok, now you're just printing the string backwards in a non-C++ way. Once again, the function is only useful (to other C++ code) if it returns something via reference, pointer, etc. Notice that the OP's reverse function returns a string. Some other answers modify the input string.

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.