gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:33:53 25 4
gpt4 key购买 nike

测试代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com