测试代码:
void modify_it(char * mystuff)
{
//last element is null i presume for c style strings here.
char test[7] = "123456";
//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.
//static char test[] = "123123";
//this is also creating memory on stack and not the heap i reckon
//and gets destroyed once the function is done with.
//char * test = new char[7];
//this does the job as long as memory for mystuff has been
//allocated outside the function.
strcpy_s(mystuff,7,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.
mystuff = test;
}
int main(void)
{
//allocate memory on heap where the pointer will point
char * mystuff = new char [7];
modify_it(mystuff);
std::string test_case(mystuff);
//this is the only way i know how to use cout by making it into a c++ string.
std::cout<<test_case.c_str();
delete [] mystuff;
return 0;
}
char *
表单的字符串。我看到的所有内容通常都需要const char*
,而不仅仅是char*
。 我知道我可以使用引用来轻松处理这个问题。或char **
发送指针并按此方式执行。但我只是想知道我是否可以只用char *
来做。无论如何,你的想法和评论加上任何例子都会非常有帮助。
答案 0 :(得分:2)
char * mystuff = new char [7]; delete mystuff;
delete mystuff
导致未定义的行为。您必须delete[]
new[]
。
答案 1 :(得分:2)
行mystuff = test;
使变量mystuff
包含test
数组的地址。但是,此赋值是函数的本地。调用者永远不会看到mystuff
的修改值。这通常适用于C / C ++:函数参数按值传递,对该值的局部修改在函数外部是不可见的。唯一的例外是,如果在C ++的参数列表中使用&
运算符,则会导致参数通过引用传递。像这样:
void modify_it(char* &str) { /* ... */ }
但是,如果你这样做,你的程序仍然无法正常工作,并可能会崩溃。那是因为test
的地址是堆栈内存,当modify_it
返回时,该内存将被覆盖。你将给调用者一个无效堆栈内存的地址,这只能导致坏事。正确的做法是以下之一:
/* function allocates, caller frees */
void modify_it(char* &str) {
str = new char[7]; // allocate enough memory for string
memcpy(str, 7, test);
}
或者这个:
/* caller allocates and frees */
void modify_it(char* str, size_t str_len) {
if (str_len < 7) { /* report an error. caller didn't allocate enough space. */ }
memcpy(str, 7, test);
}