1. ホーム
  2. C++

void* から char* への無効な変換」および「文字列定数から 'char*' への非推奨の変換」を解決 "

2022-02-12 07:21:04
<パス

まず、次のCプログラムで、動的なメモリ割り当てを使って文字列のコピーを作成し、メモリ割り当てに失敗した場合に、その作業を行うことにしましょう。 duplicate function はヌルポインタを返します。

#include 
Using
gcc
The compilation passes directly and prints the following result
Original String: testing.
Duplicated String: testing.
But when using
g++
compile, an error and warning will appear as follows
error: invalid conversion from 'void*' to 'char*' [-fpermissive] 

warning: deprecated conversion from string constant to 'char*' [-Write-strings] The reason for the error is that C++ is designed to be more secure than C and it does not automatically convert void * to other pointer types. The reason for the warning is that the program is trying to convert a string literal (which is a const char [] in C++, but a char [] in C) to a char * type, so if you want to use the g++ to successfully compile this program and get the expected results, you can change the source program to #include
gcc