I am trying to run the following code which takes string parameter and returns the length of the string in characters in C language using Visual Studio Code, but I am getting:
Error message:
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
Here is my code:
int str_length(char *mystring){
int i=0;
for(i=0; mystring[i]!='\0'; i++);
return i;
}
void alpha(){
printf("%d\n", str_length("-h=123"));
printf("%d\n", str_length(""));
}
I am stuck with this task, maybe you could provide a possible solution or some parts of the code that I have to change?
It means that you are compiling your program as a C++ program.
In C++ opposite to C string literals have types of constant character arrays.
From the C++ 17 Standard (5.13.5 String literals)
8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char” , where n is the size of the string as defined below, and has static storage duration (6.7).
But even in C the function parameter shall have the qualifier const
because the function does not change the passed string. The function can look the following way
size_t str_length( const char *mystring )
{
size_t i = 0;
while ( mystring[i] != '\0' ) i++;
return i;
}
So within the function alpha
you need to write
printf("%zu\n", str_length("-h=123"));
printf("%zu\n", str_length(""));
changing the conversion specifier from %d
to %zu
. The signed type int
can be not large enough to store the length of an arbitrary string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.