cout a char* function only prints address

I have this function to concatenate two const char*, but I'm having a lot of trouble managing to get the right return of the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream> 
#include <string.h>
using namespace std ; 

//concatenate function
char* join(const char* A, const char* B)
{
 
  //declare variable 8+1 characters
  char join[9];
  strcpy(join,A);
  strcat(join,B);
  cout << join <<'\n';
  //join both caracthers 
  char* str = join;
  return str;  
  //return the string
} 

//char* joinb(const char*, const char*) ; 



int main() { 
  //call the function
  cout << join("alpha","bet") << endl ; 


  // cout << joinb("duck","soup") << endl ; 


  return 0 ; 
} 


The first cout in the join function gives me the right result, but when setting the return i get the address (I think it is), or no memory is correctly allocated. Any solution to these?
Never return the address of a local variable. You need to create a new array with new and the suitable size. I.e.:
1
2
3
4
5
6
7
8
9
10
11
12
13
char* join(const char* A, const char* B)
{
 
  //declare variable 8+1 characters
  char *join = new char[strlen(A) + strlen(B) + 1]; // Note: + 1 for the terminating 0
  strcpy(join,A);
  strcat(join,B);
  cout << join <<'\n';
  //join both caracthers 
  char* str = join;
  return str;  
  //return the string
} 
Last edited on
Alternatively you can pass an output buffer to your function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string.h>

using namespace std;

void join(const char* A, const char* B, char *output, size_t size)
{
   if ((strlen(A) + strlen(B) + 1) < size)
     return;

  strcpy(output,A);
  strcat(output,B);
}

int main()
 { 
    char output[9];
    join("alpha","bet", output, sizeof(output));

   cout << output << endl ; 

system("pause");
  return 0 ; 
} 
@Thomas1965 - Line 8: you have the comparison reversed. I would presume you intended to return without doing anything if the combined size was larger than the size of the output buffer.

1
2
   if ((strlen(A) + strlen(B) + 1) < size)
     return;


Should be:
1
2
   if ((strlen(A) + strlen(B) + 1) > size)
     return;

@AbstractionAnon,

you are absolutely right. I should not write code without running it.
Topic archived. No new replies allowed.