+ 1
[SOLVED]Segmentation fault when using pointer in Function!
I'm trying to write a function in C to converts all small characters in a string to upper case characters and returns the number of changed characters; When I run it, I got a Segmentation fault. Can somebody helps me figure out what's wrong with my code ?? Thanks a lot. -------------------------------------------------------------------------------- #include <stdio.h> int str2upper(char *s){ int count=0; int x; for (x=0; s[x]!= '\0';x++){ if(s[x]>='a' && s[x]<='z'){ s[x]=s[x] -32; count++; } } return count; } int main() { printf("------------------------\n"); printf("%d", str2upper("aBCd") ); }
2 odpowiedzi
+ 5
In main function:
char s[] = "aBcD";
printf("%d\n", str2upper(s));
You are passing a C-string literal, which is a constant char* (read-only memory address). Pass a char array which is readable & writable to the function.
+ 1
Thank you. It works now! :D