Ok, I need an explanation to this error I am receiving in gcc:
«deprecated conversion from string constant to ‘char*'»
I receive this message when I attempt to initialize an array of char*:
Why am I receiving this error? I realize that if I declare argv as const, the compiler does not complain. How can I declare a non-const array of char*? And how come it works perfectly fine if you are passing non-const char* array parameters to main?
int main(int argc, char* argv[])
Any information would be great. Thanks!
2 Answers

Putting a series of characters between quotation marks is the way you define a string literal constant in C++. Requiring the ‘const’ to be there helps catch coding errors, such as:
// lots of other code here
See how the second line there tries to modify a constant? That’s a mistake. (See section 2.13.4 of the C++ standard.) It also makes no logical sense. It’s like trying to do: «2=3;». foo[0][0] is the literal ‘1’.
Remember, argv is an array of pointers. Those pointers point to the strings in your code. So changing argv[0][0] is like trying to change your code. It’s also like trying to do this:
If this were legal code, ‘j’ would point to the address of a constant, just like ‘foo[0]’ does in your code. And trying to modify through that pointer would make no sense, just like it doesn’t in your code. However, the compiler can catch this because it just doesn’t let you take the address of integer constants. But you can with string constants — it is still your obligation to use those pointers to constants in a way that makes logical sense.
In most cases, the compiler would have no way to know that foo[0] pointed to a constant because you didn’t declare ‘foo’ const. So the new rule is that pointers to unmodifiable constants must be const.
The fix is either to declare your constants as ‘const’ or don’t use constants for things you plan to vary.
поэтому я работаю над чрезвычайно большой кодовой базой и недавно обновлен до gcc 4.3, который теперь запускает это предупреждение:
предупреждение: устаревшее преобразование из Строковой константы в’char*’
очевидно, правильный способ исправить это-найти каждое объявление, как
или вызов функции, как:
и сделать их const char указатели. Однако это означало бы прикосновение к файлам 564, минимум, что не является задачу я хочу выполнить в данный момент. Проблема сейчас в том, что я бегу с -werror , поэтому мне нужно как-то подавить эти предупреждения. Как я могу это сделать?
23 ответов
Я верю, передает -Wno-write-strings для gcc будет подавлять это предупреждение.
любые функции, в которые вы передаете строковые литералы «I am a string literal» должны использовать char const * как тип вместо char* .
если вы собираетесь что-то исправить, исправить это правильно.
объяснение:
вы не можете использовать строковые литералы для инициализации строк, которые будут изменены, потому что они имеют тип const char* . Отбрасывая константу, чтобы позже изменить их,неопределено поведение, так что вы должны скопировать const char* строки char by char в динамически выделяемой char* строки, чтобы изменить их.
пример:
для GCC, вы можете использовать #pragma warning директивы, как пояснил здесь.
у меня была похожая проблема, я решил ее так:
является ли это подходящим способом решения этой проблемы? У меня нет доступа к foo адаптировать его к accept const char* , хотя это было бы лучшим решением (потому что foo не меняет m ).
Если это активная база кода, Вы все равно можете обновить базу кода. Конечно, выполнение изменений вручную невозможно, но я считаю, что эта проблема может быть решена раз и навсегда одним
Я не могу использовать параметр компилятора. Поэтому я повернул это:
вот как это сделать встроенным в файл, поэтому вам не нужно изменять свой Makefile.
I have a class with a private char str[256];
and for it I have an explicit constructor:
When I compile this I get the following warning:
deprecated conversion from string constant to ‘char*’
Why is this happening?
11 Answers 11
This is an error message you see whenever you have a situation like the following:
Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives you a warning about this conversion being deprecated.
So, somewhere you are missing one or more const s in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.
deprecated conversion from string constant to ‘char*’
is given because you are doing somewhere (not in the code you posted) something like:
The problem is that you are trying to convert a string literal (with type const char[] ) to char* .
You can convert a const char[] to const char* because the array decays to the pointer, but what you are doing is making a mutable a constant.
This conversion is probably allowed for C compatibility and just gives you the warning mentioned.
As answer no. 2 by fnieto — Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
However, if you want to keep your code warning-free as well then just make respective change in your code:
That is, simply cast the string constant to (char *) .
There are 3 solutions:
Arrays also can be used instead of pointers because an array is already a constant pointer.

In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.
I solve this problem by adding this macro in the beginning of the code, somewhere. Or add it in , hehe.
Maybe you can try this:
It works for me
I also got the same problem. And what I simple did is just adding const char* instead of char*. And the problem solved. As others have mentioned above it is a compatible error. C treats strings as char arrays while C++ treat them as const char arrays.
For what its worth, I find this simple wrapper class to be helpful for converting C++ strings to char * :
A reason for this problem (which is even harder to detect than the issue with char* str = «some string» — which others have explained) is when you are using constexpr .
It seems that it would behave similar to const char* str , and so would not cause a warning, as it occurs before char* , but it instead behaves as char* const str .
Constant pointer, and pointer to a constant. The difference between const char* str , and char* const str can be explained as follows.
- const char* str : Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
- str++ ; : VALID. We are modifying the pointer, and not the data being pointed to.
- *str = ‘a’; : INVALID. We are trying to modify the data being pointed to.
- char* const str : Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
- str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
- *str = ‘a’; : VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5]; .
- const char* const str : Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
- str++ ; : INVALID. We are trying to modify the pointer variable, which is a constant.
- *str = ‘a’; : INVALID. We are trying to modify the data pointed by this pointer, which is also constant.
In my case the issue was that I was expecting constexpr char* str to behave as const char* str , and not char* const str , since visually it seems closer to the former.
Also, the warning generated for constexpr char* str = «some string» is slightly different from char* str = «some string» .
- Compiler warning for constexpr char* str = «some string» : ISO C++11 does not allow conversion from string literal to ‘char *const’
- Compiler warning for char* str = «some string» : ISO C++11 does not allow conversion from string literal to ‘char *’ .
You can use C gibberish ↔ English converter to convert C declarations to easily understandable English statements, and vice versa. This is a C only tool, and thus wont support things (like constexpr) which are exclusive to C++ .