Error : Invalid conversion - c++

I am new to C++ and this is the error I keep getting and I have no idea what it is. It says that at the display function line. It has this error
invalid conversion from 'char' to 'char*' [-fpermissive]|
May I know what is the meaning of this error and how to solve it ?
void passChar()
{
char letter[] = {'H','E','L','L','O','!'};
for(int i = 0; i<6; i++)
{
while(true)
{
display(letter[i]);
swapLetter(letter[i]);
}
}
}
Here is my display function
void display(char letter[])
{
for(int i = 0 ; i<6 ; i++)
{
switchStatement(letter[i]);
}
}
Here is my swapletter function
void swapLetter(char letter[])
{
char temp = letter[0];
for(int i = 1; i < 6; i++)
{
letter[i-1] = letter[i];
}
letter[5]= temp;
}
My aim is to have endless loop for the word hello.

Your code is invalid in whole because this loop
while(true)
{
display(letter[i]);
swapLetter(letter[i]);
}
is infinite unless either display or swapLetter does not have call to exit.
As for error then it is obvious from the error message that the function expects to get some string instead of on character. So its parameter is declared something as char s[] or char *s, or const char s[], or const char *s and so on.
And even if you would pass to it your array letter it would be a mistake because your array has no the terminating zero. I think you should declare your array as
char letter[] = {'H','E','L','L','O','!', '\0'};
Or function display should be declared as
void display( char c );

Presumably because your display() function looks like the following:
void display(char* value)
{ }
letter[i] is of type char, the above function expects char*...

It means that you are passing a char as a parameter to a function that expects char*.
Your functions actually expect you to pass the entire string rather than a single character. So your code should be:
display(letter);
swapLetter(letter);
Of course, I suspect that renders the outer loop in passChar meaningless. And the infinite while(true) loop seems odd, although you claim in the question that it is intentional. In which case the code should read:
void passChar()
{
char letter[] = {'H','E','L','L','O','!'};
while(true)
{
display(letter);
swapLetter(letter);
}
}
Personally I think I would code display and swapLetter to accept char* and use the null-terminator to detect length.
void passChar()
{
char letter[] = "HELLO!";
while(true)
{
display(letter);
swapLetter(letter);
}
}
and then modify display and swapLetter to use the null-terminator to locate the end of the string.

Related

Passing the char *str inside the function

I newly started C++ and it feels pretty wired while writing Java for a while. So, I have this array,
char values[][10] = {"miami", "seattle", "berlin"};
int rows = sizeof values / sizeof values[0];
This is this is the function where I would like to pass the value,
// a function to reverse the strings
void App::reverse(char *str) {
}
When I do the loop, I can't apparently pass the value there,
for (int i = 0; i < rows; ++i) {
// first character of the string
char *firstPtr = values[i];
reverse(firstPtr);
}
The line reverse(firstPtr) provides error which I don't understand. The error message says Too few arguments, expected 2.
What is the issue here? I apologize for any mistakes as writing the C++ for the first time and the pointer stuff feels strange.
UPDATE
This is the piece of code I would like to exexute,
void App::reverse(char* str) {
// get the first character of the string
char *ptrEnd = str;
char temp;
if (str){
while (*ptrEnd) {
ptrEnd++;
}
ptrEnd--;
// as long the first adddress is lesser than the end
while (str < ptrEnd) {
temp = *str;
*str++ = *ptrEnd;
*ptrEnd-- = temp;
}
}
}
There is too little information here to be sure, but it looks like you have
using namespace std;
Somewhere in your code. Don't do this! In this case, the standard library has a function reverse() in std that takes two parameters.
Furthermore, you have void App::reverse(char *str), but that cannot be seen from void myArray::reverse(char* str), so your own reverse() cannot be called as-is - you would need to do App::reverse() if the function is a class static.

Passing pointer to char* array into function to manipulate values on Arduino

[PLEASE CHECK FINAL EDIT BELOW FOR UPDATE]
My C++ is a bit rusty (to say the least) and I'm having an issue trying to pass a char array into a function to manipulate the values. Example code below:
void myFunction(char* splitStrings,String stringToSetInLoop) {
char substringPtr[stringToSetInLoop.length()];
stringToSetInLoop.toCharArray(substringPtr, stringToSetInLoop.length());
for(int i = 0; i < 10; i++) {
splitStrings[i] = *substringPtr;
}
}
char *mySplitStrings[10];
myFunction(*mySplitStrings,String("Repeat Me"));
Serial.println(mySplitStrings[0]);
The code does not crash, but it outputs a blank line. I suspect that I need to initialize a 2 dimensional array outside the function to pass in so that memory space is allocated. I'm guessing that, although the substring pointer exists inside the function, the memory is destroyed, leaving the char* array mySplitStrings[0] pointing at nothing. Also, I think I need to pass in the reference to the array memory space, not as a pointer.
The ultimate goal here is to be able to pass a char array into a function, assign some values to it, then use those values back in the main code loop. If there's a better way to achieve this, then please let me know.
Thanks in advance. Please free me from my personal pointer/reference hell!
EDIT: Further note, this code is being run on an arduino, so the C++ is limited.
EDIT: When I try to pass in a reference to the char* pointer, I get this error, which I'm not sure how to change the function parameters to fix: error: cannot convert char* ()[10] to char for argument 1 to void myFunction(char*, String). Can anybody please take a stab at showing me a working example?
EDIT:
Thanks to the responses... I now have a working static library function that splits strings passed as a char* array. I know it's not pretty, but it does work. Thanks you to those who contributed. Code below:
void ExplodeString::explode(char* explodeResults[], String str, String delimiter) {
int delimiterPosition;
int explodeResultsCounter=0;
String subString;
do {
delimiterPosition = str.indexOf(delimiter);
if(delimiterPosition != -1) {
subString = str.substring(0,delimiterPosition);
char *subStringPtr[subString.length()+1];
subString.toCharArray(*subStringPtr, subString.length()+1);
explodeResults[explodeResultsCounter++] = strdup(*subStringPtr);
str = str.substring(delimiterPosition+1, str.length());
} else { // here after the last delimiter is found
if(str.length() > 0) {
subString = str;
char *subStringLastPtr[subString.length()+1];
subString.toCharArray(*subStringLastPtr, subString.length()+1);
explodeResults[explodeResultsCounter++] = strdup(*subStringLastPtr);
}
}
} while (delimiterPosition >=0);
}
Usage:
char* explodeResults[10];
ExplodeString::explode(explodeResults, String("cat:dog:chicken"), String(":"));
Serial.println(explodeResults[0]);
Serial.println(explodeResults[1]);
Serial.println(explodeResults[2]);
EDIT: Man, this is sooo much easier when you use the stdlib:
void ExplodeString::explode(std::vector<std::string> &explodeResults, std::string str, char delimiter) {
std::stringstream data(str);
std::string line;
while(std::getline(data,line,delimiter))
{
explodeResults.push_back(line);
}
}
Usage:
std::vector<std::string> commandsResult;
char delimiter[] = ",";
std::string _inputString = "my,string,to,parse";
ExplodeString::explode(commandsResult, _inputString, delimiter[0]);
How to pass an array of char*:
void myFunction(char* splitStrings[10], String stringToSetInLoop) {
// ...
char *mySplitStrings[10];
myFunction(mySplitStrings, String("Repeat Me"));
This will also work:
void myFunction(char* splitStrings[], String stringToSetInLoop) {
and this:
void myFunction(char** splitStrings, String stringToSetInLoop) {
Also, seems there is STL for avr platform - include it, C++ without STL is smth strange.
You are not allocating space for character arrays and just passing pointer of character array.
Instead of using char*splitStrings[10], you can use 2d char array with sufficient space to accomodate max length string. Assuming you max string length is less that 64 you can do something like this.
char splitString[10][64];
void myFunction(char**splitStrings,String stringToSetInLoop)
or
void myFunction(char splitString[][64], String stringToSetInLoop)
{
int len = stringToSetInLoop.length();
for(int i = 0; i<10; i++)
{
for(int j = 0; i<len; j++)
{
splitString[i][j] = stringToSetInLoop.charAt(j);
}
}
}

C++ char sequence function always return empty string

Just start learning C++ and trying to make a simple function that do substring with following code:
char* substring(int start, int end, const char* target)
{
size_t length = strlen(target);
char result[(length + 1)];
int iterator = 0;
for(int i = start; i < length; i++)
{
if(i <= end)
{
result[iterator] = target[i];
iterator++;
}
}
result[iterator] = '\0';
cout << result << endl; // This give correct result "aya";
return result;
}
When I use these function on main method:
int main(int argc, char** argv) {
char some_text[] = "Saya Makan";
char* sub = substring(1, 3, some_text); // No string returned
cout << "Substring Result is: " << sub;
return 0;
}
It give output is like this:
aya
Substring Result is:
RUN SUCCESSFUL (total time: 44ms)
As seen on the result, my function isn't returning anything but empty string although a line of code before return, the "result" variable echoed result correctly. Would you please explain to me what is happening inside my function, am I missing something?
You are returning pointer to a local array which is not required to live beyond the function.
You need to make the buffer persist beyond the scope of the function by allocating it dynamically using malloc. And ofcourse remember to free it later.
Oh just noticed its C++.
So drop the idea of malloc and free simply use std::string and not char *.

How to copy data starting from end of the array in C/C++

I have a function void copy(char *temp,char input[length]). What I need to do is copy the values of temp into input array but starting from the end of the input array.
I did not frame the question correctly.
Here's what I'm trying to do.
I've input array of length 20. I get a temp array with values 'test'. Then I would like to copy temp in the input array where input[19]=t,input[18]=e etc.
Now when I call the function again, and if I want to copy xyz to input array, then input[15]=x,input[14]=y,input[13]=z.
I want to do this till I fill the input array with all the values.
void copy(char *temp,char input[])
This is the function definition.
Now let's look at what we have to do,
char* temp={"abcde"};
char input[100]={};
//I want to move data from temp into input array such that
printf("%c",input[95]); // gives output as a
printf("%c",input[96]); // gives output as b
This is what I've written so far.
char* copy(char* ptr,char data[])
{
int start=sizeof(data)/sizeof(char)-strlen(data);
int end=start-strlen(ptr);
int j=0;
int counter=0;
for(counter=start;counter>end;counter--)
{
data[counter]=ptr[j++];
}
printf("%s",data);
return data;
}
When I call this function I get another error in this manner,
char data[100]={};
char* temp={"abcde"};
char* output=copy(temp,data);
data=output;
incompatible types in assignment of ‘char*’ to ‘char [100]’ for data=output line
That is already implemented as an algorithm:
std::reverse_copy( input, input+length, output );
In a related note, the signature of your function:
void copy(char *temp,char input[length])
actually means:
void copy(char *temp,char *input)
That is, the length of the input array is not part of the signature of the function, and it will not be checked by the compiler. Consider passing the size as an extra argument or else passing the array by reference. Additionally the source array is not modified, so it should be a const char*
If it's a string, you can use strlen to check the size of the input string and then copy it reversed. On the other hand if it is an array of chars, which doesn't end with '\0', you have to take a new parameter for the length.
First case (you said copy the values of temp into input array, so we're copying the content of temp into input, dismissing its name):
void copy(char *temp, char input[length])
{
for(int i = strlen(temp) - 1; i >= 0; i--)
{
input[i] = temp[i];
}
}
Second case:
void copy(char *temp, char *input, size_t length)
{
for(int i = length - 1; i >= 0; i--)
{
input[i] = temp[i];
}
}
Otherwise you can use the standard library function reverse_copy.

cannot convert parameter 1 from 'char' to 'const std::basic_string<_Elem,_Traits,_Ax> &'

I am getting abpve error at line str.append(ch); in below code.
I basically want to append str with each char 'ch'.
If someone know the issue please correct my error.
int extract(unsigned char data, char i); // Signature of extract function
void decoded(istream& input,ostream& output)
{
int cnt;
int x;
input.read((char*)&x,sizeof(x));
cout<<x;
cnt=x;
string str;
char ch;
for ( ; ; )
{
char c;
input.read((char*)&c,sizeof(char));
if ( input )
{
//read_bit(c,output);
for (int i=7; i>=0; i--)
{
if(cnt)
{
cnt--;
ch=(char)(((int)'0')+extract(c, i));
str.append(ch);// I am getting error at this line.
if(huffmanFindTable[str])
{
output.write((char*)&(huffmanFindTable[str]),sizeof(char));
str.clear();
}
else
{
}
}
}
}
else
break;
}
}
Like the compiler says, there is no member function with the signature
str.append(ch);
You can use either
str.append(1, ch);
or the simpler
str.push_back(ch);
string::append has no member function taking a char as argument. You can append null-terminated char arrays or other stringS.
You can only append a "sequence" of character to a string. "append" is an operation on two (sequence) vector (take the word vector in a more generic sense) like objects.
You can do the following:
str.append(1, ch);
str+=ch;