How to reverse a string in C? -


i trying reverse string when run code , program crashes . doing wrong? program supposed show @ first , string without being reversed , reversed.

p.s: if haven't noticed 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;     (i=0; i<j; i++, j--)     {         temp=str[i];         str[i]=str[j];         str[j]=temp;     }     printf(str); } 

reversing function fine, problem lies elsewhere.

char* str = "hello world"; 

here, str points string literal, immutable. placed in data segment of program , modification of it's content 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;     (i=0; i<j; i++, j--)     {         temp=str[i];         str[i]=str[j];         str[j]=temp;     }     printf(str); } 

another option strrev() function.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -