如何在运行时设置指向Null的指针(C++)

Stu*_*art 0 c++ null pointers

现在我有一个指针设置在我的2D数组中的一行.我希望该指针停止指向该行,但我稍后将使用指针进行其他操作.我只是想知道如何在指针初始化并指向一行后取消设置指针.

double* tempRow;
tempRow = (double*) malloc(size * sizeof(double));
   ...
tempRow = NULL;
Run Code Online (Sandbox Code Playgroud)

不会将tempRow变量与数组行取消链接.为什么不?

我想知道我是否应该使用C代替.使用矢量时会有开销吗?

Mic*_*son 11

虽然你已经写了将tempRow设置为NULL,但它不会释放你已分配的内存.为此你需要

free(tempRow);
tempRow = NULL;
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用C++作为标记建议,那么最好使用C++ new/delete

double* tempRow;
tempRow = new double[size];
   ...
delete [] tempRow;
tempRow = NULL;
Run Code Online (Sandbox Code Playgroud)

您甚至可以使用STL为您处理内存分配.

std::vector<double> tempRow(size);
// You can access the data, in a similar way to an array
tempRow[5] = tempRow[4]+tempRow[3];

// If you really need to access the underlying pointer, (To pass to another 
// function for example) you can do this. Note that the pointer will be valid
// until the vector is destroyed or modified in certain ways that can cause the
// vector to reallocate its memory. So you can't use this to pass data to a 
// function that destroys or takes ownership of the passed in pointer.

fn_requiring_pointer( &temp[0] );

// The memory used in tempRow will get cleaned up automatically when the 
// object goes out of scope
//
// If I really need to free up the memory used in it early I can use a swap 
// hack. (iirc tempRow.clear() isn't guaranteed to release the memory)
std::vector<double>().swap(tempRow); // Unneeded in most cases.
Run Code Online (Sandbox Code Playgroud)

还试图将tempRow指针重用于不相关的东西可能不是必需的.只需创建一个具有不同名称的新指针.从多个不同的不相关目的重用变量形式可能使代码很难在以后理解.

  • 我被告知`std :: vector <double> tempRow(size)`是使用`new []`和`delete []`的一个很好的替代方法,但我是一个C++ noob,所以接受这个建议一粒盐. (6认同)
  • @Michael:如果你需要指针,`&temprow [0]`会给你.这是一个老式的数组指针. (2认同)

dre*_*lax 6

我也是C++的新手,但不久前,有人告诉我,使用std::vector是一种更安全的处理数据数组的方法.

  • 添加更多元素时自动重新分配.
  • 与来自的东西一起使用的迭代器#include <algorithm>.
  • 边界保护与.at(index)元素访问.
  • 不需要杂乱的指针跟踪.
  • C阵列样式访问operator[].
  • RAII.

你会声明一个这样的矢量:

std::vector<double> tempRow(size);

tempRow[0] = 3.00;
tempRow[1] = 1.00;

// no need to use delete[] or free(), it will destruct itself
// and relinquish its resources automatically.
Run Code Online (Sandbox Code Playgroud)