Definition and Usage of C++ Pointer Functions
A pointer function in C++ is a function that returns a pointer. It can return a pointer to any data type, including primitive data types, custom data types, arrays, etc.
The form of defining a pointer function is as follows:
返回类型* 函数名(参数列表) {
// 函数体
}
The return type represents the type of pointer that the function returns, * is the identifier for pointer type, the function name is the name of the function, and the parameter list is the parameters the function can accept.
The usage of pointer functions is as follows:
- Return a pointer pointing to a basic data type.
int* getNumber() {
int* ptr = new int;
*ptr = 10;
return ptr;
}
int main() {
int* numPtr = getNumber();
cout << *numPtr << endl; // 输出:10
delete numPtr;
return 0;
}
- Return a pointer to a custom data type.
struct Person {
string name;
int age;
};
Person* createPerson(string name, int age) {
Person* ptr = new Person;
ptr->name = name;
ptr->age = age;
return ptr;
}
int main() {
Person* personPtr = createPerson("Alice", 20);
cout << personPtr->name << endl; // 输出:Alice
cout << personPtr->age << endl; // 输出:20
delete personPtr;
return 0;
}
- Return a pointer pointing to an array.
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
int main() {
int* arrPtr = createArray(5);
for (int i = 0; i < 5; i++) {
cout << arrPtr[i] << " "; // 输出:1 2 3 4 5
}
delete[] arrPtr;
return 0;
}
It is important to note that after using a pointer function to return a pointer, you need to manually release the memory to prevent memory leaks. You can use delete to release memory pointed to by a single pointer, or use delete[] to release memory pointed to by an array.