指向预分配内存的指针作为输入参数并让函数填充它

时间:2010-04-05 19:15:16

标签: c++

测试代码:

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;
}
  1. 如果函数中有静态数组,为什么它不起作用?
  2. 如果我在函数中使用new分配了内存,它是在堆栈还是堆上创建的?
  3. 如果我有一个需要复制到char *表单的字符串。我看到的所有内容通常都需要const char*,而不仅仅是char*
  4. 我知道我可以使用引用来轻松处理这个问题。或char **发送指针并按此方式执行。但我只是想知道我是否可以只用char *来做。无论如何,你的想法和评论加上任何例子都会非常有帮助。

2 个答案:

答案 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);
}