从函数C ++设置指针变量

时间:2014-06-27 00:27:27

标签: c++ pointers memory-address

如何从另一个函数调整char *指针。现在我在我的代码中,看起来地址正在同步,所以我觉得我做错了请帮忙。

void adjustVar(char* pointer, size_t i) {
   //pointer address at this point = 0x00000000
   pointer = new char[i];
   //pointer address at this point = 0x003db708
}

int main(void) {
   char* p = nullptr;
   size_t size = 5;
   //p Address at this point 0x00000000
   newBuffer(p, size);
   //p Address at this point 0x00000000
   delete[] p;
   return 0;
}

1 个答案:

答案 0 :(得分:2)

我可以考虑以下选项:

选项1:从adjustVar返回分配的内存。

char* adjustVar(size_t i) {
   char* pointer = new char[i];
   return pointer;
}

选项2:使用对指针的引用。

void adjustVar(char*& pointer, size_t i) {
   //pointer address at this point = 0x00000000
   pointer = new char[i];
   //pointer address at this point = 0x003db708
}