Today, when I realized the strlen function, I met a very interesting warning:
warning:deprecated conversion from string constant to ' char* ' [-wwrite-strings]
1#include <stdio.h>2 3 intStrlenChar*str) {4 Char*s;5 for(S=STR; *s; s++);6 returnS-str;7 }8 9 intMain ()Ten { One Char*S1 ="ABC"; A CharS2[] ="ABC"; -printf"%d\n", strlen (S1)); -printf"%d\n", strlen (S2)); the return 0; -}
Since the previous contest has been avoiding pointers, it has been used to define "[]", which is the way arrays are. Now the use of "*" is defined by the way the pointer is to produce warning, for a moment still baffled its solution.
But I think, with the function of the value should be no relationship here, so I delete the code is left only the definition of the statement, and compile again.
1 #include <stdio.h>23int main ()4{5 Char *s1 " ABC " ; 6 return 0 ; 7 }
Yes, it's just this definition statement, and the warning is still there.
A general understanding of the following warning message is that the deprecated conversion from a string constant to a char pointer? See Foggy, but think is not let write!
2 3 int main () 4 5 char *s1 = " ABC ; 6 *s1 = " 7 return 0 8 }
This is going to get an error!
Error:invalid conversion from ' const char* ' to ' char ' [-fpermissive]
So, do not let the modified value, is not a constant!
So I was determined to add the const:
1 #include <stdio.h>23int main ()4{5 Const Char *s1 "ABC"; 6 return 0 ; 7 }
The world is quiet!
But why does a string pointer have to be const-decorated?
The brain shows, it's obvious that we are assigning a string constant "ABC" address to the S1 pointer, then the S1 pointer should be received (canonical) using a const pointer.
So what do you do if you want to change it? The answer is an array:
1#include <stdio.h>2 3 4 intMain ()5 {6 Const Char*S1 ="ABC";7 CharS2[] ="111";8*S2 ='2';9printf"%s\n", S2);Ten return 0; One}
So, this time the output value is "211".
Problems encountered by the writing strlen function.