Меню

Ошибка invalid conversion from const char to char fpermissive

Why I’m getting this error?

invalid conversion from 'const char*' to 'char' [-fpermissive]

Here is my simple sketch:

const char data = "should";

//I have also tried:
//const char* data = "should";

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print("this " + data + " work");
}

VE7JRO's user avatar

VE7JRO

2,49715 gold badges24 silver badges29 bronze badges

asked Feb 5, 2018 at 11:40

Kirill's user avatar

2

const char data = "should";

In this case data is a single character, not a string. So it can store 's' but not "should".

Serial.print("this " + data + " work");

No, that will never work, even if you get your data types correct. You do not concatenate strings like that. All you are doing is attempting to add the addresses of two string literals to the address of a string constant. If that were possible (the compiler doesn’t let you) you’ll get gibberish (or a crash) as it tries to print out whatever is at that address.

Instead break it down:

Serial.print("this ");
Serial.print(should);
Serial.print(" work");

answered Feb 5, 2018 at 11:55

Majenko's user avatar

MajenkoMajenko

104k5 gold badges75 silver badges133 bronze badges

11

A char can only store one character.

and const char* data can store a pointer to a string.

You can copy it with strcpy:

const char* data = malloc(7);
if (data != 0)
{
    strcpy(data, "should");
}

This will create 7 bytes, which can store «should» (adding 1 byte extra for the byte to denote the end of a string.

However, in your case you can create a const string like:

const char data[7]="should";

or

const char data[]="should";

answered Feb 5, 2018 at 11:44

Michel Keijzers's user avatar

Michel KeijzersMichel Keijzers

12.7k7 gold badges36 silver badges56 bronze badges

4

Zzepish

0 / 0 / 0

Регистрация: 27.11.2012

Сообщений: 14

1

27.11.2012, 02:27. Показов 44756. Ответов 6

Метки нет (Все метки)


Я в С++ новенький. Поэтому опыта еще нет, да и знаний мало.
ПОдскажите пожалуйста, чего вылетает ошибка invalid conversion from ‘const char*’ to ‘char*’:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
 
using namespace std;
 
main(){
 
       char numbers[50];
       
       numbers[0]="Hi";
       numbers[1]="World";
       numbers[2]="!";
      
       for(int i=0, count=2;numbers[i]!=false;i++){
       
               cout<<numbers[i]<<"n";
       
       }
            
       system("PAUSE");
       
       return 0;
 
}

p.s. кодю на DEV C++

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

Регистрация: 29.11.2010

Сообщений: 13,453

27.11.2012, 02:30

2

Элементы массива numbers — это char, а не chars. Ты пихаешь на место одной буквы несколько.
Возвращаемый тип функции надо указывать явно.

Добавлено через 1 минуту
И наверняка ведь ругается не так, как ты указал, а invalid conversion from ‘const char*’ to ‘char’



0



Zzepish

0 / 0 / 0

Регистрация: 27.11.2012

Сообщений: 14

27.11.2012, 02:37

 [ТС]

3

Цитата
Сообщение от MrGluck
Посмотреть сообщение

Элементы массива numbers — это char, а не chars. Ты пихаешь на место одной буквы несколько.
Возвращаемый тип функции надо указывать явно.

исправил на chars- вообще нет такого определения. Сделал:

C++
1
2
3
numbers[0]="H";
       numbers[1]="W";
       numbers[2]="!";

по одному символу- все-равно ругается.

Цитата
Сообщение от MrGluck
Посмотреть сообщение

Добавлено через 1 минуту
И наверняка ведь ругается не так, как ты указал, а invalid conversion from ‘const char*’ to ‘char’.

Действительно, ошибся

Добавлено через 2 минуты
MrGluck, омг. исправил на

C++
1
 char * numbers[50];

и все заработало. Почему так?



0



MrGluck

Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

Регистрация: 29.11.2010

Сообщений: 13,453

27.11.2012, 02:40

4

Цитата
Сообщение от Zzepish
Посмотреть сообщение

исправил на chars- вообще нет такого определения. Сделал:

C++
1
2
3
numbers[0]="H";
       numbers[1]="W";
       numbers[2]="!";

по одному символу- все-равно ругается.

Действительно, ошибся

Добавлено через 2 минуты
MrGluck, омг. исправил на

C++
1
 char * numbers[50];

и все заработало. Почему так?

chars не существует. Есть char (буква), есть массив букв, char* . Теперь вы создаете массив из 50 массивов букв.
Элемент массива под индексом 0 теперь массив букв и туда благополучно влезет все, что вы задаете в скобках. Раньше это была лишь одна буква (char) и то, что стояло справа от = просто не влезало.

Добавлено через 44 секунды

по одному символу- все-равно ругается.

C++
1
2
3
numbers[0]='H';
numbers[1]='W';
numbers[2]='!';



1



Zzepish

0 / 0 / 0

Регистрация: 27.11.2012

Сообщений: 14

27.11.2012, 02:41

 [ТС]

5

Цитата
Сообщение от MrGluck
Посмотреть сообщение

chars не существует. Есть char (буква), есть массив букв, char* . Теперь вы создаете массив из 50 массивов букв.
Элемент массива под индексом 0 теперь массив букв и туда благополучно влезет все, что вы задаете в скобках. Раньше это была лишь одна буква (char) и то, что стояло справа от = просто не влезало.

Добавлено через 44 секунды

C++
1
2
3
numbers[0]='H';
numbers[1]='W';
numbers[2]='!';

Благодарю) но почему на ВЫ)



0



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

Регистрация: 29.11.2010

Сообщений: 13,453

27.11.2012, 02:48

6

Цитата
Сообщение от Zzepish
Посмотреть сообщение

Благодарю) но почему на ВЫ)

Не по теме:

Стараюсь с незнакомыми людьми на вы, правда под вечер за этим не уследить и метод обращения скачет туда-сюда.



1



0 / 0 / 0

Регистрация: 27.11.2012

Сообщений: 14

27.11.2012, 03:11

 [ТС]

7

MrGluck, Вы- множественное число)
Давай на ты (я, ведь, один, да и каждый в единственном числе)

Добавлено через 10 минут
MrGluck, А в пм как написать?



0



How to fix invalid conversion from ‘const char to ‘char errorIn C++, the error invalid conversion from ‘const char*’ to ‘char*’ happens when you try to pass a nonmodifiable constant char for char. C++ throws this error to let you know you are performing an operation that is not possible.

In this post, you will learn the causes of this error and how to avoid it in the future. Read further to be able to solve this issue in the future.

Contents

  • Why Is Invalid Conversion From ‘Const Char*’ to ‘Char*’ Error Happening?
    • – Converting Constant Char* Into Char *
    • – Generating the Error in C++
    • – Changing String Literals
  • How To Fix Invalid Conversion Error
    • – Using Single Quotes
    • – Using C Style Strings
  • FAQ
    • – What Is Const Char*?
    • – Can I Pass Char * As Const * Argument?
    • – What Is a Constant Pointer to a Constant?
    • – What Is the Meaning of a Constant Pointer?
    • – Why Use Constant Char *?
  • Conclusion

Why Is Invalid Conversion From ‘Const Char*’ to ‘Char*’ Error Happening?

The invalid conversion from ‘const char*’ to ‘char*’ error pops up when you try to add the address of strings to the address of a character. When you use double quotes, C++ compiles it as a single-character string literal whose representation is const char * – a pointer to a constant character.

– Converting Constant Char* Into Char *

A char in C++ acts as a pointer to a location with a value of type char that can be modified. You can also modify the value of the pointer to point to another location. On the other hand, although a const char* pointer can be altered, it points to a location with a value of type char that cannot be altered.

Its application is in strings of characters that do not need modification. For instance, when declaring characters, you should use single quotes (”) instead of double quotes (“”).

You cannot explicitly convert constant char* into char * because it opens the possibility of altering the value of constants. To accomplish this, you will have to allocate some char memory and then copy the constant string into the memory. That is the only way you can pass a nonconstant copy to your program.

– Generating the Error in C++

Suppose you are creating a game that requires one to provide the initial for their first name and then choose a number between 0 and 5. In C++, you can decide to do it like so:

#include <iostream>
using namespace std;
int main()
{
char name;
char first_name= “D”;
loop:
cout << “Please provide your first name initials (e.g. David – D): “;
cin >> name;
if (first_name==name)
{
int number;
int choice;
cout << “Congrats your name was saved succesfully”;
loop1:
cout << “Please enter a number between 0 and 5: “;
cin >> number;
if (number!=2)
{
cout << “Sadly you cannot progress :)”;
cout << “To play again press 1 or close the program by pressing 2 :)”;
cin >> choice;
if (choice=2)
goto loop2;
else
goto loop1;
}
if (number=2)
{
cout << “Congratulations “;
cout << first_name;
cout << ” you won”;
goto loop2;
}
}
else
{
cout << “please try again”;
goto loop;
}
loop2:
return 0;
}

However, running this code generates the error. It arises from the declaration of first_name as char with double quotes (“”).

– Changing String Literals

Suppose you intend to capture phone numbers for people who visit your program. You can choose to define guest as a variable as follows:

#include <iostream>
using namespace std;
int main()
{
char name = “Guest”;
int number;
cout<< name;
cout<<“, please provide your phone number up to 9 digits: “;
cin>> number;
cout<< name;
cout<<“, your phone number “;
cout<<number;
cout<<” has been saved successfully.”;
return 0;
}

If you run this program, you will get the same error as before. The reason is you are using “” instead of ” when defining char in the program. The statement ‘char name = “Guest”‘ generates a string literal that is stored in the read-only segment of the compiler memory.

Standards in both C++ and C indicate that string literals have a static storage duration. So, any attempt to change them will result in undefined behavior. The variable name is a pointer that stores the address of the string literal.

The error in this code arises because ‘name’ is not a constant pointer.

Invalid conversion from ‘const char*’ to ‘char*’ error can be fixed in C++ by declaring a char using C style strings. Also, C++ lets use single quotes (”) instead of using double quotes (“”) to declare char. Using single quotes is the simplest way of overcoming this error in C++.

– Using Single Quotes

In the previous example that requires you to provide your first name initial, you can solve the error by using single quotes (”) for the first_name variable. You can accomplish this like so:

#include <iostream>
using namespace std;
int main()
{
char name;
char first_name= ‘D’;
loop:
cout << “Please provide your first name initials (e.g. David – D): “;
cin >> name;
if (first_name==name)
{
int number;
int choice;
cout << “Congrats your name was saved succesfully”;
loop1:
cout << “Please enter a number between 0 and 5: “;
cin >> number;
if (number!=2)
{
cout << “Sadly you cannot progress :)”;
cout << “To play again press 1 or close the program by pressing 2 :)”;
cin >> choice;
if (choice=2)
goto loop2;
else
goto loop1;
}
if (number=2)
{
cout << “Congratulations “;
cout << first_name;
cout << ” you won”;
goto loop2;
}
}
else
{
cout << “please try again”;
goto loop;
}
loop2:
return 0;
}

– Using C Style Strings

Say you are creating a program that captures the phone number of guests to a certain event. You can define the guest variable as like C style strings. Here is how you can accomplish this :

#include <iostream>
using namespace std;
int main()
{
const char *name = “Guest”;
int number;
cout<< name;
cout<<“, please provide your phone number: “;
cin>> number;
cout<< name;
cout<<“, your phone number “;
cout<<number;
cout<<” has been saved successfully.”;
return 0;
}

Notice how the guest variable is defined as a constant character. At this point, it is worth noting that you cannot change the value pointed by the variable although you can alter the pointer itself. Also, keep in mind that the position of the asterisk does not matter since the eventual outcome is a constant char. In C++, the * operator usually denotes a pointer to an object in memory.

In this example, defining the “name” as const and adding the * operator helps you avoid the error.

FAQ

– What Is Const Char*?

In C++, it functions as a pointer to a constant char. What this means is you cannot modify the char in question.

– Can I Pass Char * As Const * Argument?

Generally, it is possible to pass char * to something that anticipates a constant char * without explicitly casting since it is safe to do so. However, you cannot pass a constant char * into an element that anticipates a char* without explicitly casting it since it is not safe to accomplish this. In other words, you cannot pass something that is not meant to be changed into something that can modify it. In both C and C++, you cannot change the values of constants once you initialize them.

– What Is a Constant Pointer to a Constant?

When you define a constant pointer to a constant, it means that you cannot change the address the variable points to, nor can you modify the value in the address.

– What Is the Meaning of a Constant Pointer?

It refers to a pointer that cannot modify the address it holds. In other words, you can think of a constant pointer as a variable that is unable to point to any other variable.

– Why Use Constant Char *?

There are various reasons why you should consider using const char *. First, it ensures your code does not alter the data it points to. Second, it prevents you from inadvertently writing somewhere you are not meant to. As well, it may help the compiler establish possible optimizations.

Conclusion

The C++ compiler will throw this error at you if you try to convert constant char into char. Here is a quick recap:Invalid conversion from ‘const char to ‘char error

  • The error stems from trying to convert const char into char in C++
  • One way you can avoid this error is by using single quotes when defining char in C++
  • Also, you can define the char as constant in a pointer

With this understanding, you can now avoid this error altogether in C++.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Hi All,

I am following the tutorial from the below link with same versions mentioned in it.
https://github.com/EdjeElectronics/TensorFlow-Object-Detection-on-the-Raspberry-Pi

However I have encountered the below error message.

pi@raspberrypi:~/protobuf-3.5.1/python $ python3 setup.py build —cpp_implementation
running build
running build_py
running build_ext
building ‘google.protobuf.pyext._message’ extension
arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I../src -I/usr/include/python3.7m -c google/protobuf/pyext/descriptor_database.cc -o build/temp.linux-armv7l-3.7/google/protobuf/pyext/descriptor_database.o -Wno-write-strings -Wno-invalid-offsetof -Wno-sign-compare
arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I../src -I/usr/include/python3.7m -c google/protobuf/pyext/repeated_composite_container.cc -o build/temp.linux-armv7l-3.7/google/protobuf/pyext/repeated_composite_container.o -Wno-write-strings -Wno-invalid-offsetof -Wno-sign-compare
arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I../src -I/usr/include/python3.7m -c google/protobuf/pyext/descriptor_containers.cc -o build/temp.linux-armv7l-3.7/google/protobuf/pyext/descriptor_containers.o -Wno-write-strings -Wno-invalid-offsetof -Wno-sign-compare
google/protobuf/pyext/descriptor_containers.cc: In function ‘bool google::protobuf::python::descriptor::_GetItemByKey(google::protobuf::python::PyContainer*, PyObject*, const void**)’:
google/protobuf/pyext/descriptor_containers.cc:69:45: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
(((charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0):
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
google/protobuf/pyext/descriptor_containers.cc:172:13: note: in expansion of macro ‘PyString_AsStringAndSize’
if (PyString_AsStringAndSize(key, &name, &name_size) < 0) {
^~~~~~~~~~~~~~~~~~~~~~~~
google/protobuf/pyext/descriptor_containers.cc:69:45: error: invalid conversion from ‘const char
’ to ‘char*’ [-fpermissive]
((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0):
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
google/protobuf/pyext/descriptor_containers.cc:189:13: note: in expansion of macro ‘PyString_AsStringAndSize’
if (PyString_AsStringAndSize(key, &camelcase_name, &name_size) < 0) {
^~~~~~~~~~~~~~~~~~~~~~~~
error: command ‘arm-linux-gnueabihf-gcc’ failed with exit status 1

What version of protobuf and what language are you using?
Version: master/v3.6.0/v3.5.0 etc.
—> Protobuf version 3.5
Tensorflow version that I am using is 1.14.0
Language: C++/Java/Python/C#/Ruby/PHP/Objective-C/Javascript
—> Python 3.7.3
What operating system (Linux, Windows, …) and version?
—> Raspbian
What runtime / compiler are you using (e.g., python version or gcc version)
—> python 3.7.3
[GCC 8.2.0] on linux

What did you do?

Steps to reproduce the behavior:
followed steps from the above tutorial link untill the error message.
I got error on this line. «python3 setup.py build —cpp_implementation»

What did you expect to see
Compile without errors

What did you see instead?
Error message.

Make sure you include information that can help us debug (full error message, exception listing, stack trace, logs).

Anything else we should know about your project / environment
I am trying to build object detection model on my Raspberry pi 4 model B.

Please let me know for any additional details required for resolving it.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка internet explorer обнаружена ошибка
  • Ошибка java failed to validate certificate the application will not be executed