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

标签 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*

我知道我可以使用引用来轻松解决这个问题。或者 char ** 发送指针并以这种方式执行。但我只是想知道我是否可以仅使用 char * 来做到这一点。无论如何,您的想法和评论以及任何示例都会非常有帮助。

最佳答案

char * mystuff = new char [7];
delete mystuff;

delete mystuff 导致未定义的行为。您必须删除[]新[]的内容。

关于c++ - 指向预分配内存的指针作为输入参数并让函数填充它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2580536/

相关文章:

c++ - 如何使用 C++ win32 API 连接消息框文本中的值?

c++ - 在结构中初始化一个字符串对象

c++ - 直接写入 std::string 的 char* 缓冲区

c++ - 对象类型如何在编译时未知?

c++ - 为什么默认的默认构造函数取决于它是在类内部还是外部声明?

c++ - 对一个类中的一个 vector 进行排序,第二个 vector 应与第一个 vector 一起移动

c++ - CEF base::ThreadRestrictions::AssertIOAllowed() 断言在应用程序退出时失败

c++ - 函数内部动态分配的内存泄漏

c++ - 这两个高阶函数定义之间有什么区别吗?

C++:指向虚拟成员函数的单态版本的指针?