|
Team Leader
|
![]() |
| 13Aug2007,23:24 | #11 |
|
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.
|
|
Go4Expert Member
|
|
| 13Aug2007,23:52 | #12 |
|
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
|
|
Team Leader
|
![]() |
| 14Aug2007,02:35 | #13 |
|
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. |
|
Go4Expert Member
|
|
| 14Aug2007,07:41 | #14 |
|
Sorry but how should i define my function where should i change.
Thankyou for your reply. |
|
Team Leader
|
![]() |
| 14Aug2007,12:06 | #15 |
|
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. |
|
Team Leader
|
![]() |
| 14Aug2007,13:12 | #16 |
|
Code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
char a[] = "hi ";
char b[] = "world";
cout<<endl<<strcat(a,b);
return 0;
}
|
|
Team Leader
|
![]() |
| 14Aug2007,14:05 | #17 |
|
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.
|
|
Team Leader
|
![]() |
| 14Aug2007,19:00 | #18 |
|
sorry, it was quick and dirty modifying the code he had. Hopefully he gets the idea
|

