append or concatenate to a char*

hi guys, ^^

how can i append text or concatenate text in a const char *???
in this function, if i put "A Journey to the Center of the Earth", it will return "Jules Verne", but i want "Jules Verne" inside brackets, like "[Jules Verne]", i was thinking if its possible to concatenate two brackets.
I have tried strcpy and sprintf.

here is the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static const char * author_req(const char *book)
{
    const char *result = "";
    const char *temp;

    if (!book){
		return result;
	}
	
    temp = get_author(book);
    if (temp){
		result = temp; /* concatenate here?? */
		return result;
	}
	
    return result;
}


thanks ^^
Appending to a char* means that the location to where that char* points to has some free space. String literals have none. Also, the const in const char* means that whatever it points to cannot be tampered with.
What you could do is make a copy of the string and do whatever you like with it, however this would require dynamic allocation (should I explain why?) and if you did that, you'd forget to delete it, resulting in a memory leak.
If you can, use std::string. It would make the task trivial.
If you can't, you should change the function to void author_req(const char* book, char* result) so that the caller gets to decide how he wants to allocate memory.
ok, thanks ^^.

i did this...

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

static const char * author_req(const char *book)
{
    const char *result = "";
    const char *temp;
    std::string str;

    if (!book){
		return result;
	}
	
    temp = get_author(book);
    if (temp){
                
                str = "[";             // i put temp
                str += temp;       // inside brackets
		str += "]"            // like i wanted ^^
		result = str.c_str();

                return result;
                
	}
	
    return result;
}


and it works!!!!
thanks hamsterman ^^


it should not have memory problems, right?

Right. std::strings clean up after themselves. As an exercise, you may consider growing a char* with dynamic memory allocation yourself.
ok ^^
thanks.

ill mark this as solved.
Topic archived. No new replies allowed.