DaWei's Avatar, Join Date: Dec 2006
Team Leader
Well, as you can see, my program concatenated char arrays to both a char array and a string. You can get a char array from the string by using the .c_str () method.
kaustubh's Avatar, Join Date: Aug 2007
Go4Expert Member
I am sorry i tried doing that but here is the code

Code:
#include<iostream>
#include<string>
using namespace std;

const char add(char a[], char b[])
 {
string str = a;
str+= b;
const char *c_str1 = str.c_str ( ); 
return *c_str1;
}
 int main()
{
char a[] = "hi";
char b[] = "world";
cout<<endl<<add(a,b);
return 0;
}

OUTPUT:
h
you see output gives h when i want "hi world ",please help how should i change the function.
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You have defined your add function to return a single char. You are then returning the dereferenced value of the string. The first byte of that string is a single char, precisely as you have asked it to do.

At some point you are going to have to realize that your code does as you instruct it to do, not as you wish that it would do in the absence of explicit instructions.
kaustubh's Avatar, Join Date: Aug 2007
Go4Expert Member
Sorry but how should i define my function where should i change.
Thankyou for your reply.
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You cannot declare a local variable in a function and return a pointer to it. The variable goes out of scope when the function returns. The pointer then points to junk. You either need to declare the variable outside the function (as I did with "destination"), or you need to dynamically allocate memory for it inside the function. That memory, not being local, will persist. In the latter case, you must remember to free the memory.

I suggest you make a class for string manipulation and have the add method be part of that class. Then the destructor would be used to free the memory.

You are missing some very basic understanding of the language. You need to study. It will be more time-effective then bopping in and out of a forum for every little thing you do wrong.
jwshepherd's Avatar, Join Date: Aug 2007
Team Leader
Code:
#include<iostream>
#include<string>
using namespace std;

 int main()
{
char a[] = "hi ";
char b[] = "world";
cout<<endl<<strcat(a,b);
return 0;
}
DaWei's Avatar, Join Date: Dec 2006
Team Leader
JW, your solution corrupts variable a and relies on a specific method of auto-variable generation to prevent it from corrupting other memory locations and causing a crash.
jwshepherd's Avatar, Join Date: Aug 2007
Team Leader
sorry, it was quick and dirty modifying the code he had. Hopefully he gets the idea