user2684719
user2684719

Reputation:

How get rid of warning: deprecated conversion from string constant to char*

How to get rid of the below warnings.

 warning: deprecated conversion from string constant to char* [-Wwrite-strings]

Here is code.

#include<stdio.h>
#define MY_STRING       "drivers.txt"   

void printMyString(char str[]){
    printf(str);  
}


int main(){
    printMyString(MY_STRING);   
}

Upvotes: 1

Views: 3153

Answers (4)

unwind
unwind

Reputation: 399863

Probably by making the function:

static void printMyString(const char *str)
{
   printf("%s", str);
}

This does three things better:

  1. The function is static (a minor point).
  2. The argument is const char *, since string literals are read-only.
  3. The printing is done using %s, since it's dangerous to pass (potentially unknown) strings directly to printf(). If the string contains a %, that will cause printf() to attempt formatting, but of course no formatting data is present. This can lead to crashes.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

I think you are compiling the program in C++.

In C++, string literals have type const char[], not the same as char [] in C.

And it's better not to pass strings to printf as format specifier, it may cause potential security problems.

Change it to:

void printMyString(const char *str){
    printf("%s", str);  
}

Upvotes: 6

trojanfoe
trojanfoe

Reputation: 122391

Change the str parameter definition to const:

void printMyString(const char *str) {
    printf(str);  
}

Upvotes: 0

Karthik T
Karthik T

Reputation: 31952

Change

void printMyString(char str[]){
    printf(str);  
}

to

void printMyString(const char str[]){  //or const char* since that is all that it is.
    printf(str);  
}

This is ofcourse more relevant to C++ since it is illegal there to hold a string literal in a non const pointer.

You could also compile it in gcc instead of g++.

Upvotes: 0

Related Questions