chevron_left
226 points
13 5 3

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';
char ptr[1];
ptr[0] = c;
ptr[1] = '\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.

#include <iostream>

using namespace std;

void function(const char* ptr)
{
	cout << "Your character is " << ptr << endl;
}

int main()
{
	char c = 'O';
	char ptr[1];
	ptr[0] = c;
	ptr[1] = '\0';  // add the NULL-terminating character
	function(ptr);
}

Result:

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 !

More Posts

Invalid conversion from char to const char* C++ hhh98hd - Aug 2
Incompatible types in assignment of 'char*' to char hhh98hd - Aug 3
Warning deprecated conversion from string constant to ‘char*’ hhh98hd - Aug 2
C++ invalid conversion from const char* to char Lalit Kumar - Apr 19, 2020
Get the size of an array C++ hhh98hd - Aug 5
How to find the size of the variable char and char array in C++? Lalit Kumar - Jun 19, 2020
ERROR invalid type argument of unary '*' (have 'int') Lalit Kumar - Jun 26, 2020
make_unique in c++11 hhh98hd - Sep 4
Initialize a pointer C++ hhh98hd - Aug 24
const_cast in C++ hhh98hd - Aug 11