When working with char arrays or char pointers, you may encounter the error “Invalid conversion from char to const char* [-fpermissive]”. In this article, I will point out the root cause of the error along with the solution to the error. So let’s begin !
Basically, char and char* are 2 compltely different data types: char is a variable used for storing ASCII characters or values from 0 to 255 while char* is used to store addresses of char variables. This error may arises when you try to pass a char variable to a function that only accept char*. const char* is a a kind of pointer which cannot change its pointee after assignment.
So in case we just want to pass 1 character, what should we do ?
The nature of an array variable is just the pointer to address of the first element, we can pass an array as const char* parameter:
char c = 'A';
ptr = c;
ptr = '\0';
Although the character only accounts for one element, we must always remember to add the NULL-termination character (‘\0’) or else your program would produce undefined behaviours or even crashings.
using namespace std;
void function(const char* ptr)
cout << "Your character is " << ptr << endl;
char c = 'O';
ptr = c;
ptr = '\0'; // add the NULL-terminating character
Your character is O
Although the above method can be used as a work-around, however, if char pointer is not your only choice, I would recommend to use STL string as it is more robust and have built-in methods for convenience.
I have shown you the reason as well as remedy for the error “Invalid conversion from char to const char* [-fpermissive]”. If you have ane advices or questions for me, please leave comments.
Happy coding !