c - Segmentation fault on reverse string function -
I am trying to write a simple function that reverses the string:
#include & lt; Stdio.h & gt; #include & lt; String.h & gt; # Include & lt; Stdlib.h & gt; Four * reverse SRR (four * s) {INSLLL = Stellen (S); Int i; Four floating; For (i = 0; i <(sLen / 2); i ++) {// swap temp = s [i]; S [i] = s [slen-a-1]; S [slen-a-1] = temporary; } Return S; } Main () {int num = 64; Four * str; Str [0] = 'one'; * (Str + 1) = 'B'; * (Str + 2) = '\ 0'; Printf ("% s% d% s", str, strlen (str), reverse str (str); }
When I call this function for some reason, I get the error of the segmentation fault core dump. I can not see the place where it happened. Anyone?
Your problem is how you are creating the string in the first place:
four * str; Str [0] = 'one'; * (Str + 1) = 'B'; * (Str + 2) = '\ 0'; By declaring str
, it returns an arbitrary so that it is str [0]
undefined behavior .
You can fix it with something:
four letters [3]; Str [0] = 'one'; * (Str + 1) = 'B'; * (Str + 2) = '\ 0'; Although
though I'm not sure that you are mixing due to dereferencing methods ( base [idx]
and * Are base + IDX)
).
Alternatively, you can try the following short options:
four letters [3]; Strcpy (str, "ab"); Four str [] = "now";
Comments
Post a Comment