'When calling the function this error [Error] incompatible types in assignment of 'char' to 'char [40]'
I am returning the *res (which is value resultant string after concatenating strings) in the function. When I call this function and store the result in the char array then it gives me error [Error] incompatible types in assignment of 'char' to 'char [40]' .I want to concatenate two strings in the function and return the concatenating string from function.Kindly help to solve to this problem
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
char strConcat(char *,char *);
char input1[10],input2[12],resultantString[40];
cout<<"Enter the 1st String=";
cin.getline(input1,10);
cout<<"Enter the 2nd String=";
cin.getline(input2,10);
//faulty code
resultantString=strConcat(input1,input2);
cout<<resultantString;
}
// st1 means String1 and St2 means string2 which we want to concat.
char strConcat(char *st1,char *st2)
{
char *res;
while(*st1!='\0')
{
*res=*st1;
*st1++;
*res++;
}
while(*st2!='\0')
{
*res=*st2;
*st2++;
*res++;
}
*res='\0';
return *res;
}
Solution 1:[1]
First off, remove using namespace std;
, it's a bad habit.
Next up, move the function declaration void strConcat(char *,char *);
out of main and make it the same type as the definition, this is your error, you declare strConcat
to return void
first but then you define it to return char
, the compiler still thinks it returns void
and thus when you're trying to assign something to it the compiler complains.
Next up, make main
return int
, your current definition isn't valid.
Next, indent your code so not only the compiler can read it but other humans too.
And the most important tip here, remove all of those static-sized arrays and that homebrewed strCat
function and use std::string
and it's operator+
for concatenation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |