Strange error converting integer to char array

I want to write a function converting an integer to a null-terminated char array. Here is the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void inttochar(char* kchar, int k) {

	int j;
	stringstream sstr;
	string kstr;
	sstr << k;
	kstr=sstr.str();
	kchar=new char[kstr.length()+1];
	for(j=0;j<kstr.length();j++) kchar[j]=kstr[j];
	kchar[kstr.length()]=0;
}

int main() {

	char *ch;
	inttochar(ch, 12);
	fprintf(stdout, ch);
}


However running this prints 'inttochar' to the screen! How does the name of the function end up in *ch?
closed account (z05DSL3A)
I don't know why 'inttochar' is being displayed, *ch is not being affected by the function.

If you want to change the pointer (ch) you have to pass a pointer to the pointer. All you are doing is making a copy of ch and using the copy not ch.
You change the value of kchar when you assign the return of new char[] to it. However this change is lost when the functions ends because kchar is local to your function. Your char* ch outside the function is therefore still uninitialized when you come to print it.

Try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void inttochar(char*& kchar, int k) {

	int j;
	stringstream sstr;
	string kstr;
	sstr << k;
	kstr=sstr.str();
	kchar=new char[kstr.length()+1];
	for(j=0;j<kstr.length();j++) kchar[j]=kstr[j];
	kchar[kstr.length()]=0;
}

int main() {

	char *ch;
	inttochar(ch, 12);
	fprintf(stdout, ch);
}

What I have done is to pass the pointer by reference, meaning kchar is no longer a copy of the parameter you pass in (ch) but it is a direct reference to it. That means that the pointer you pass in (ch) gets updated, rather than only a copy that is local to the function.
That works, thanks! I've never seen * followed by & on a single variable before, have to think about that for a bit.
Last edited on
closed account (z05DSL3A)
...also don't forget to delete[] ch when you are done with it.
Topic archived. No new replies allowed.