0

Here is my question:

Write a function void reverse(char s[]) that reverses a character string. For example, “Harry” becomes “yrraH”.

And here is my code :

void reverse(char s[]);
int main()
{
    char s [] = "Harry";
    reverse(s);
    cout << s << endl;

    system("PAUSE");
    return 0;
}

void reverse(char s[])
{
    int length = strlen(s);
    int c, i ,j;

    for(int i=0, j=length-1 ; i<j ; i++, j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

It works perfectly to reverse the string. However, I was asked to do it in pointer. So from what I thought, first I assign a p pointer to get the first char in string. Then I assign a q pointer to get the last char of string. The I loop thru to reverse the array. But when I tried to do this to get the last char:

char *q = strlen(s-1);

I got an error. Can somebody help me fix this using pointer?

Updated portion

if (strlen(s) > 0(
{
char* first = &s[0];
char*last = &s[strlen(s)-1];
while(first < last)
{
char temp = *first;
*first = *last;
*last = temp;
++first;
--last;
}
}
Yvonne
  • 63
  • 1
  • 4
  • 12
  • What does " I was asked to do it in pointer" mean? You could just replace `char[]` with `char*`. – juanchopanza May 13 '13 at 07:57
  • Ya but I did attempt. I did not just throw the question here without solution. There is an error when I try to count the length and assign it to pointer. – Yvonne May 13 '13 at 07:58
  • 3
    Look at what `strlen()` returns and what you are assigning it to. – Philip Kendall May 13 '13 at 07:58
  • 2
    strlen() returns an integer, not a char * – Gung Foo May 13 '13 at 07:58
  • Tell them your version more readable and less error-prone than one using pointers and that you don't want to use them. That you wrote unit tests for your code and it runs correctly. – Daniel Daranas May 13 '13 at 07:58
  • @Dukeling Yes. For homework questions, you generally don't want to give a complete answer without any explanations. Homework is about figuring it out yourself (mostly). – J. Steen May 13 '13 at 07:58
  • you likely wanted `strlen(s)-1`: misplaced closing `)`; + strlen returns a `size_t` – ShinTakezou May 13 '13 at 07:58
  • 1
    @Yvonne Then post the actual code with pointers and which doesn't work, not the alternative version that works but that "they" don't want. – Daniel Daranas May 13 '13 at 07:59
  • Ok then how do I get the last char in string and assign it to pointer q? – Yvonne May 13 '13 at 08:01
  • @J.Steen In my opinion, you should approach all questions the same. In general no-one should ever give a complete answer without an explanation to anything. If I ask a question, homework or not, I'd be rather frustrated with an answer that's just code, I prefer to know why something doesn't work or how something works. IMO, that's why [the homework tag was deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated). – Bernhard Barker May 13 '13 at 08:04
  • 4
    @Dukeling That's true, but some of us just don't want to do someone's homework for them. So, it's nice if the person asking is up-front about that. –  May 13 '13 at 08:07
  • @Yvonne, here is a little tip, that can help you -- `char[]` can be replaced with `char*`. The access to the elements remains the same, through the `operator[]`. By the way, if you have a `char s[] = "Hello";` and `char* z = s;` ---- `s[2]` is the same as `z[2]` and the same as `*(z + 2)`. – westwood May 13 '13 at 08:10
  • @Dukeling The homework tag was deprecated because people treated the questions **unfairly** harsh, berating people extra much for not doing their own homework (hah) first. I agree with you, in principle, but homework questions should be approached in a more guiding manner rather than completely answering them. In my opinion. =) – J. Steen May 13 '13 at 08:11
  • 1
    @yvonne Have a look at [this](http://pw1.netcom.com/~tjensen/ptr/ch3x.htm) too.Its a tutorial on arrays and pointers in `c`. You seem to be missing a bit of basics on arrays. – Suvarna Pattayil May 13 '13 at 08:13
  • @J.Steen Agreed.The problem starts when people with homework just post the question expecting an answer with minimal effort from their side. – Suvarna Pattayil May 13 '13 at 08:15
  • Thanks ShinTakezou, Apokal and Suvp. I've updated my solution for this question above. =) – Yvonne May 13 '13 at 08:30
  • @Yvonne After the update, what is your question? – Daniel Daranas May 13 '13 at 08:34
  • It's fixed. I just want to let those who assume that I did not put in effort and just simply throw question here without any codes know that I've solved it. Thanks DanielDaranas by the way. – Yvonne May 13 '13 at 08:38

3 Answers3

7

Note that Bartosz Marcinkowski's answer may be all your instructor is looking for. But the way I'd write this is:

void reverse( char* str )
{
    char* end = str + strlen( str );
    while ( end > str ) {
        -- end;
        swap( *str, *end );
        ++ str;
    }
}

This has the advantage of handling the special cases of empty strings and single character strings correctly. One could also argue that it is more idiomatic, because it uses a half open interface, which is ubiquitous in C++. It will prepare you for iterators, which always define half open intervals (and are uses more often than pointers for this sort of thing).

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • What does str + strlen(str) do? Sum up the total char of string? Or get the last char of str? – Yvonne May 13 '13 at 08:39
  • It adds the length of the string (`strlen(str)`) to the pointer. In other words, it results in a pointer to the trailing `'\0'`. I would guess that part of the goal of requiring you to use pointers would be to familiarize you with pointer arithmetic. `str + strlen( str )` is far more idiomatic than `&str[ strlen( str ) ]`. (Whether this is a good thing or not is another question. But it _is_ the way C and C++ work, and are normally written.) – James Kanze May 13 '13 at 08:45
  • Wouldn't `std::reverse(str, str + std::strlen(str))` be more idiomatic c++? :) – clstrfsck May 13 '13 at 08:49
  • @msandiford Certainly. No C++ programmer would write anything else in production code. But it won't teach him much about pointers and pointer arithmetic, which I suspect is the goal of the exercise. – James Kanze May 13 '13 at 09:09
  • @EitanT You'd usually declare `swap` to take (non-const) references. Which means that the compiler will actually pass pointers, under the hood. But this is only the most widespread convention; passing pointers is also a valid solution. – James Kanze May 13 '13 at 09:11
  • @JamesKanze Yes, I mistook this question for [tag:c]. – Eitan T May 13 '13 at 09:12
  • @EitanT But it's a good point: everything he does in the code he shows is valid C. – James Kanze May 13 '13 at 09:29
2

Try something like that.

char* left = &s[0];
char* right = &s[length-1];
for(; left<right ; left++, right--)
{
    c = *left;
    *left = *right;
    *right = c;
}

And read this http://www.cplusplus.com/doc/tutorial/pointers/

Bartosz Marcinkowski
  • 6,651
  • 4
  • 39
  • 69
  • I do in this way. See my updated portion and it works. Thanks alot. – Yvonne May 13 '13 at 08:25
  • You should use `std::swap` in the loop. Or if he cannot use library functions, the swap should still be a separate function. – James Kanze May 13 '13 at 08:25
  • Also, if you wanted to be idiomatic, you'd use a half open interval, like everything else in C++. (In this particular case, using a half open interval is a little less obvious, but it's a good habit to get into in general.) – James Kanze May 13 '13 at 08:27
  • Please don't link to cplusplus.com, there are much better resources such as http://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome – pmr May 13 '13 at 08:28
  • And finally: if passed a one character string, this results in undefined behavior. (Or an empty string, for that matter.) – James Kanze May 13 '13 at 08:28
  • @JamesKanze I am currently still a novice in C++ and learning for pointer right now by the way. I guess in future I might be using std::reverse or swap. Thanks a lot – Yvonne May 13 '13 at 08:31
  • @Yvonne It's obviously a learning exercise, since otherwise, you'd obviously use `std::reverse`. But even as a learning exercise, it would be cleaner to put the swap in a separate function. – James Kanze May 13 '13 at 08:37
  • @Yvonne Also, if you're a novice: you should learn how to use standard containers (like `std::string`) and the functions in the standard library _before_ you address pointers. (But writing a `reverse` function yourself which uses pointers is a good exercise, once you get to pointers.) – James Kanze May 13 '13 at 08:42
1

Try this code for reversing string.

void reverse(char str[], int len)
{
    char *fptr = str;
    char *lptr = str + len -1;
    char ch = 0;
    while(fptr < lptr)
    {
            ch = *fptr;
            *fptr = *lptr;
            *lptr = ch;
            *fptr++;
            *lptr--;
    }
}
Daemon
  • 1,575
  • 1
  • 17
  • 37