pointer to preallocated memory as an input parameter and have the function fill it
Posted
by djones2010
on Stack Overflow
See other posts from Stack Overflow
or by djones2010
Published on 2010-04-05T19:15:16Z
Indexed on
2010/04/05
19:33 UTC
Read the original article
Hit count: 159
c++
test code:
void modify_it(char * mystuff)
{
char test[7] = "123456"; //last element is null i presume for c style strings here.
//static char test[] = "123123"; //when i do this i thought i should be able to gain access to this bit of memory when the function is destroyed but that does not seem to be the case.
//char * test = new char[7]; //this is also creating memory on stack and not the heap i reckon and gets destroyed once the function is done with.
strcpy_s(mystuff,7,test); //this does the job as long as memory for mystuff has been allocated outside the function.
mystuff = test; //this does not work. I know with c style strings you can't just do string assignments they have to be actually copied. in this case I was using this in conjunction with static char test thinking by having it as static the memory would not get destroyed and i can then simply point mystuff to test and be done with it. i would later have address the memory cleanup in the main function. but anyway this never worked.
}
int main(void)
{
char * mystuff = new char [7]; //allocate memory on heap where the pointer will point
cool(mystuff);
std::string test_case(mystuff);
std::cout<<test_case.c_str(); //this is the only way i know how to use cout by making it into a string c++ string.
delete [] mystuff;
return 0;
}
- in the case, of a static array in the function why would it not work.
- in the case, when i allocated memory using new in the function does it get created on the stack or heap?
- in the case, i have string which needs to be copied into a char * form. everything i see usually requires const char* instead of just char*.
I know i could use reference to take care of this easy. Or char ** to send in the pointer and do it that way. But i just wanted to know if I could do it with just char *. Anyway your thoughts and comments plus any examples would be very helpful.
© Stack Overflow or respective owner