C code to reverse a string - including NULL character at the end of string -
1.) possible reverse string including null character (which means “abcd” represented 5 characters, including null character.)
2.) in current implementation, doesn't take 1.) account, getting segmentation error during swapping. ie while assigning: *str = *end;
void reverse(char *str) { char * end = str; char tmp; if (str) { // handle null string while (*end) { // find end character ++end; } --end; // last meaningful element while (str < end) // terminal condition: str , end meets in middle { tmp = *str; // normal swap subroutine *str = *end; // str advance 1 step *end = tmp; // end 1 step str++; end-- ; } } return; }
your function correct. seems problem trying reverse string literal. may not change string literals. immutable. attemp change string literal results in undefined behaviour of program.
from c standard (6.4.5 string literals)
7 unspecified whether these arrays distinct provided elements have appropriate values. if program attempts modify such array, behavior undefined
only take account better write
if ( *str )
instead of
if (str)
or if want check poinetr not null then
if ( str && *str )
in case decrement
--end;
will valid if original string empty.
nevertheless function defined following way shown in demonstrative program
#include <stdio.h> char * reverse( char *s ) { char *last = s; while ( *last ) ++last; if ( last != s ) { ( char *first = s; first < --last; ++first ) { char c = *first; *first = *last; *last = c; } } return s; } int main( void ) { char s[] = "hello arshdeep kaur"; puts( s ); puts( reverse( s ) ); }
the program output is
hello arshdeep kaur ruak peedhsra olleh
Comments
Post a Comment