Home >Backend Development >C++ >How Are Pointers Passed as Arguments in C , by Value or by Reference?

How Are Pointers Passed as Arguments in C , by Value or by Reference?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 16:56:141018browse

How Are Pointers Passed as Arguments in C  , by Value or by Reference?

Passing Pointer Arguments: Pass by Value or Pass by Reference in C

In C , arguments are typically passed by value, including pointers. When a pointer is passed as an argument, the address of the object it points to is copied into the function's parameter. This means that any changes made to the pointer itself within the function will not be reflected outside the function.

However, changes made to the object pointed to by the pointer will be reflected, as the original object is modified through the pointer reference. Therefore, it is acceptable and a standard procedure to use a pointer to a pointer as an argument to a function to modify the pointer value within that function.

For example, consider the following code:

void ModifyPointer(int **ptr) {
  *ptr = new int;
}

int main() {
  int *ptr = new int;
  ModifyPointer(&ptr);
  return 0;
}

In this code, the ModifyPointer function takes a pointer to a pointer as an argument. Within the function, a new int object is allocated and the pointer referenced by the parameter is updated to point to the new object.

Since the original pointer is modified through the pointer to pointer, the change is reflected in the main function. The ptr variable now points to the newly allocated int object.

In C , it is preferred to use references instead of pointers whenever possible. References provide similar functionality to pointers but with cleaner syntax and stronger type checking.

For instance, the above example can be rewritten using a reference:

void ModifyPointer(int *&ptr) {
  ptr = new int;
}

int main() {
  int *ptr = new int;
  ModifyPointer(ptr);
  return 0;
}

The above is the detailed content of How Are Pointers Passed as Arguments in C , by Value or by Reference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn