C++中的雙重指針(double pointer)通常用于指向數組、結構體或其他復雜數據結構。以下是一些使用雙重指針進行內存管理的技巧:
int** create2DArray(int rows, int cols) {
int** array = new int*[rows];
for (int i = 0; i < rows; ++i) {
array[i] = new int[cols];
}
return array;
}
class Node {
public:
int data;
Node* next;
};
Node** createLinkedList(int size) {
Node** head = new Node*[size];
for (int i = 0; i < size; ++i) {
head[i] = new Node();
head[i]->data = i;
head[i]->next = nullptr;
}
return head;
}
void swap(int** a, int** b) {
int* temp = *a;
*a = *b;
*b = temp;
}
void traverse2DArray(int** array, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << array[i][j] << " ";
}
cout << endl;
}
}
在使用雙重指針進行內存管理時,需要注意內存分配和釋放。確保在不再需要動態分配的內存時釋放它,以避免內存泄漏。