Reputation:
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
Reputation: 399863
Probably by making the function:
static void printMyString(const char *str)
{
printf("%s", str);
}
This does three things better:
static
(a minor point).const char *
, since string literals are read-only.%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
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
Reputation: 122391
Change the str
parameter definition to const
:
void printMyString(const char *str) {
printf(str);
}
Upvotes: 0
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