egidra
egidra

Reputation: 9087

In C, strings giving me warnings about initialization discarding qualifiers

I am getting the following warning for two lines of my code.

initialization discards qualifiers from pointer target type

The two lines are the sources of the warning.

function (const char *input) {
  char *str1 = input;
  char *str2 = "Hello World\0";
}

I think the first line gives an error because I try to assign a const char* to a char*. How would I fix that?

Upvotes: 0

Views: 130

Answers (2)

user1118321
user1118321

Reputation: 26395

You need to declare it const:

const char *str1 = input;

Upvotes: 2

ouah
ouah

Reputation: 145899

void function (const char *input) {
 char *str1 = input;
 char *str2 = "Hello World\0";
}

in C an object of type char * cannot be initialized with an object of type const char *.

You have do this instead:

const char *str1 = input;

Also a string literal like "Hello World" is already null terminated, there is no need to add the null character yourself, do this instead:

char *str2 = "Hello World";

Upvotes: 1

Related Questions