Append a char* to a char**.

closed account (18hRX9L8)
Hello,

Is it possible to append a char* to a char** without knowing the size of any of the variables?

For example:
1
2
3
4
5
char **tokens; // This is "Hello, ", "World!", " My ", "name ", "is ", "Usandfriends!";
char *token = " Hello World!";

strapp(tokens, token);
tokens; // This is now "Hello, ", "World!", " My ", "name ", "is ", "Usandfriends!", " Hello World!"; 


Function would look like this:
1
2
3
4
// Appends string to string array.
void strapp(char **tokens, char *token) {
	// ... Something ...
}


NOTE: I cannot use std::vector, std::map, std::string, std::pair, std::deque, or std::list.

Thank you,
Usandfriends
Last edited on
can you use std::deque or std::list or are stl containers not allowed?
You get a pointer. It can be invalid. It can point to location of local variable. It can point to a member of an array. It can point to dynamically allocated memory block large enough for one or multiple variables.

Your function call creates a copy of a pointer. It cannot adjust the pointer that the caller has.

" Hello Wordl!" is a string constant. Non-const pointer to it is hardly appropriate.
closed account (18hRX9L8)
Smac89 wrote:
can you use std::deque or std::list or are stl containers not allowed?

I can't use those either.

keskiverto wrote:
You get a pointer. It can be invalid. It can point to location of local variable. It can point to a member of an array. It can point to dynamically allocated memory block large enough for one or multiple variables.

Your function call creates a copy of a pointer. It cannot adjust the pointer that the caller has.

" Hello Wordl!" is a string constant. Non-const pointer to it is hardly appropriate.

It was just an example. The char** variable will not hold constants. It will hold words from a file. [EDIT] I'm not sure I understood what you were trying to say. [/EDIT]
Last edited on
closed account (18hRX9L8)
This is what I got so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdlib>
#include <cstdio>

// Appends string to string array.
char** strapp(char **tokens, char *token, int maxw) {
	char **tmp = (char**)malloc(sizeof(char*) * (maxw+1));
	
	for(int x = 0; x < maxw; x++) {
		tmp[x] = tokens[x];
	}
	
	tmp[maxw] = token;
	printf("%s\n",tmp[maxw]);
	
	free(tmp);
	return tmp;
}

int main(void) {
	char **tokens;
	tokens = strapp(tokens, (char*)"hello world!", 0);
	printf("%s", tokens[0]);
}


But it prints "hello world" for the first printf but the second printf prints out 3 random ASCII characters.
Last edited on
Line 15. Deallocate tokens, not tmp.

Btw, look at realloc.
closed account (18hRX9L8)
Thanks! So I got rid of line 15 and it works! Does tmp deallocate automatically as soon as the program is over or does it create a leak?
Last edited on
Topic archived. No new replies allowed.