My Function To Convert Function To Char Array?

1
2
3
4
5
6
7
8
void Func_StrToAry(string strtemp, LPTSTR lptemp)
{
	char* temp = new char[strtemp.size()+1];
	temp[strtemp.size()]=0;
	memcpy(lptemp,temp,strtemp.size());


}


so the method works fine but I'm trying to create a void function of the above code which would have 2 arguments 1 a string like "Hi", which would then be placed inside AN ARBITRARY memory buffer like if you have a char array like char ary[3]; You could pass this to the function like
StrToAry("Hi", ary);

and that would then place Hi into your ary.

The above code doesn't work though any ideas on if this is possible and how would you do it it's confusing?

Sorry for replaying to myself but I think I found a suitable function here look at this is this acceptable to use something like 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
27
28
29
30
#include <iostream>
#include <string>

using namespace std;

char* fstr(string one)
{
	char* temp = new char[one.size()+1];
	temp[one.size()]=0;
	memcpy(temp,one.c_str(),one.size());
    return (temp);
	delete temp;

}

int main()
{

	char cone[50];
	char ctwo[50];
	memcpy(cone,fstr("hi"),3);
	memcpy(ctwo,fstr("how are you"),12);

	cout << cone << " and " << ctwo << endl;




	return 0;
}


Memory wouldn't be left hanging since it's deleted on the fly as soon as the function is over right but with that data you can permanently copy it into ANOTHER array of memory is this ok?
No.
It should have been delete[], but things below the return will never execute, as you already returned.
I don't understand what you want. You do know about std::string ¿so why go back to char* ?

You could just use strcpy
Memory wouldn't be left hanging since it's deleted on the fly as soon as the function is over right but with that data you can permanently copy it into ANOTHER array of memory is this ok?


Memory is never freed here. What happens on line 11? So do you ever reach line 12?

Regarding the original code:

Don't allocate memory in the function. Simply copy it over to the buffer supplied. This isn't very safe of course, since the function doesn't know how large the buffer is. Or, just use std::strcpy instead of defining your function since you're basically trying to reimplement that functionality.

Last edited on
Topic archived. No new replies allowed.