1

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?

Jason
  • 36,170
  • 5
  • 26
  • 60
onix012
  • 33
  • 4
  • In `c++` the compiler is correct. A string literal must be const since 2011 / c++11 – drescherjm Sep 07 '22 at 19:14
  • 2
    If you are trying to do this in C, you should be using a C compiler. – Avi Berger Sep 07 '22 at 19:15
  • 1
    Did you name the file with a .c extension? Was gcc used or g++? – drescherjm Sep 07 '22 at 19:15
  • 1
    Does this answer your question? [Why is conversion from string constant to 'char\*' valid in C but invalid in C++](https://stackoverflow.com/questions/20944784/why-is-conversion-from-string-constant-to-char-valid-in-c-but-invalid-in-c) and [Deprecated conversion from string literal to 'char*'](https://stackoverflow.com/questions/9650058/deprecated-conversion-from-string-literal-to-char) – Jason Nov 04 '22 at 17:04

1 Answers1

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335