开发者

String reverse program throws exception

开发者 https://www.devze.com 2023-01-16 08:34 出处:网络
// ExampleCodes.cpp : Defines the entry point for the console application. // #include \"stdafx.h\" #include<stdio.h>
// ExampleCodes.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;    

char* stringReverse(char* s)    
{    

    char temp, *p,*q;    
    q = s;    
    while( *(++q));    
    for( p = s; p &lt; --q; p++)    
    {    
        temp = *p;    
        *p = *q;     
        *q = temp;    
    }    
    return s;    
}    


int _tmain(int argc, _TCHAR* argv[])    
{    

    stringReverse("开发者_JS百科StringReverse");    
    return 0;    
}    


You can't modify constant string literals.

stringReverse("StringReverse");

You could use a character array instead:

char str[] = "StringReverse";


String literals, like "StringReverse", are not allowed to be modified in C. Use an array:

char str[] = "StringReverse";
stringReverse(str);

Note that your stringReverse() function has undefined behaviour if you feed it a zero-length string.


You never allocated any memory for p. You can try p = new char[sizeof(s)];


Perhaps you should write something like this:

// in - string to reverse
// out - buffer for reversed string
// l - size of in

StringReverse(char* in, char* out, int l) {
  for (int i=0;i<l;i++) {
    out[l-(i+1)] = in[i];
  }
}

*There is very very little to no speed difference between [] and *(p++) / *(p--)


Well I was going to clean up the awful source in the OP but instead I'll just post a cleaner version:

#include <stdio.h>
#include <string.h>

void reverse_string(char *s)
{
    char *q = s + strlen(s);
    for (char *p = s; p < --q; p++)
    {
        char temp = *p;
        *p = *q;
        *q = temp;
    }
}

int main()
{
    char s[] = "StringReverse";
    reverse_string(s);
    puts(s);
    return 0;
}

I hope for your sake Amit that you're still a student.

Update0

This is actually pure C, so learn from and awe at its performance but don't start writing C++ like this.

0

精彩评论

暂无评论...
验证码 换一张
取 消