c - Segmentation fault on reverse string function -
i'm trying write simple function reverses string:
#include <stdio.h> #include <string.h> #include <stdlib.h> char* reversestr(char*s) { int slen=strlen(s); int i; char temp; (i=0;i<(slen/2);i++) { //swap temp=s[i]; s[i]=s[slen-i-1]; s[slen-i-1]=temp; } homecoming s; } main() { int num=64; char*str; str[0]='a'; *(str+1)='b'; *(str+2)='\0'; printf("%s %d %s" ,str,strlen(str),reversestr(str)); }
when phone call function reason segmentation fault core dumped error. can't spot place caused. anyone?
your problem lies in how you're creating string in first place:
char*str; str[0]='a'; *(str+1)='b'; *(str+2)='\0';
the declaration of str
gives arbitrary value dereferencing str[0]
undefined behaviour.
you can prepare like:
char str[3]; str[0]='a'; *(str+1)='b'; *(str+2)='\0';
although i'm not sure why you're mixing dereferencing methods (base[idx]
, *(base+idx)
).
alternatively, seek more concise options of:
char str[3]; strcpy (str, "ab"); char str[] = "ab";
c
No comments:
Post a Comment