简体   繁体   中英

How to reverse a string in C?

I am trying to reverse a string but when I run the code , the program crashes . What am I doing wrong? The program is supposed to show at first , the string without being reversed and then reversed.

PS: If you haven't noticed I am totally new in C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseString(char* str);
int main()
{
    char* str = "Hello World";
    printf(str);
    reverseString(str);
    return 0;
}
void reverseString(char* str)
{
    int i, j;
    char temp;
    i=j=temp=0;

    j=strlen(str)-1;
    for (i=0; i<j; i++, j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
    printf(str);
}

Reversing function is fine, the problem lies elsewhere.

char* str = "Hello World";

Here, str points to a string literal, that is immutable. It is placed in data segment of your program and modification of it's content will always result in crash.

Try this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseString(char* str);
int main()
{
    char str [256];
    strcpy_s(str, "Hello World");
    printf(str);
    reverseString(str);
    return 0;
}
void reverseString(char* str)
{
    int i, j;
    char temp;
    i=j=temp=0;

    j=strlen(str)-1;
    for (i=0; i<j; i++, j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
    printf(str);
}

Another option is strrev() function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM