Pointers and Chars Arrays

Hi,

I have to concatenate three strings using only pointers without any other kind of std::function or subscripting, I can use only pointer arithmetics. I have wrote a code that manages the pointer I have created to free store chars array allocated but when I am trying to get the value from function I got only a nullptr as set before function's call. I guess it is a problem of scope but I do not know how to solve this because in every way I have a run-time error.

This is my code:
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//
//  main.cpp
//  Concatenate Strings
//
//  Created by Leonardo Urbano on 15/08/15.
//  Copyright (c) 2015 Leonardo Urbano. All rights reserved.
//

#include <iostream>
#include "std_lib_facilities.h"

char* cat_dot(const char* s1, const char* s2, const char* s3)
{
    char* p = new char[20];
    while (*s1 != '\0')
    {
        *p = *s1;
        ++p;
        ++s1;
    }    
    while (*s2 != '\0')
    {
        *p = *s2;
        ++p;
        ++s2;
    }
    while (*s3 != '\0')
    {
        *p = *s3;
        ++p;
        ++s3;
    }
    
    return p;
}

int main(int argc, const char * argv[])
{
    char* s1 = new char[10]{'N','a','p','o','l','e','o','n','e','\0'};
    char* s2 = new char[2]{'|','\0'};
    char* s3 = new char[11]{'B','o','n','a','p','a','r','t','e','\0'};
    // E.G. cout << *s1 << " " << s1;  ----->   *s1 = N and s1 = Napoleone;
    char* p = nullptr;
    p = cat_dot(s1,s2,s3);
    cout << "Concatenated string is: " << p << endl;
    
    return 0;
}


Thank you!
Last edited on
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
#include <iostream>

std::size_t len( const char* cstr )
{
    std::size_t n = 0 ;
    if( cstr != nullptr ) while( *cstr++ ) ++n ;
    return n ;
}

char* cat_dot(const char* s1, const char* s2, const char* s3)
{
    char* p = new char[ len(s1) + len(s2) + len(s3) + 1 ]; // +1 for the null terminator
    
    char* temp = p ; // make a copy; we want to return p unmodified

    if(s1) while(*s1) *temp++ = *s1++ ;
    if(s2) while(*s2) *temp++ = *s2++ ;
    if(s3) while(*s3) *temp++ = *s3++ ;
   
    *temp = 0 ; // null terminate // *** EDIT: bug-fix: s3 may be null 

    return p;
}

int main()
{
    std::cout << cat_dot( "Napoleone", " | ", "Boneparte" ) << '\n'
              << cat_dot( "Napoleone", "|", "Boneparte" ) << '\n'
              << cat_dot( "Napoleone", nullptr, "Boneparte" ) << '\n' ;
              
    // note: ignoring leaks for brevity          
}

http://coliru.stacked-crooked.com/a/d7e5253e2872bf17
Last edited on
Thank you JLBorges! I wish one day to write in C++ as you have just done! :O
Topic archived. No new replies allowed.