深入理解pointer in C++:第二重

  • Overview

Debate about pointers can stretch for miles, and you would need to go really far to master it all.

  • What is a Pointer?

Pointer is a variable that stores a memory address.

A pointer is declared using the * operator before an identifier.

As C++ is a statically typed language, the type is required to declare a pointer. This is the type of data that will live at the memory address it points to.

0x0 is 0 in hexadecimal representation, which means no memory address for a pointer.

The memory address of any variable can be accessed using the & operator.

  • How to declare a pointer

  1. declare a pointer while assigning its address a value

    int *numberPointer = new int(3);
    

    Instantiating a variable with the new operator always returns a pointer

  2. dd

  • How to modify the value at a pointer’s memory

The value at the memory address pointed to can be accessed with the dereference operator, *.

*numberPointer = 8;
  • How to understand the asterisk operator * in pointers

  1. To declare a pointer variable

    int *numberPointer = 8;
    
  2. To access the value a pointer points to

    *numberPointer = 8;
    
  • Why use pointers?

In C++, variables are passed to a function by value. When calling a function with an argument, a new variable is instantiated internally and assigned the value passed in the function call. Any modifications to the value inside the function are performed to this new variable; the variable that was invoked with the function call is unchanged.

void function_name(int x)
{
    ...
}

A function can be written to perform the same task but instead accept a pointer as the argument. This lowers the memroy footprint of the program. Unnecessary duplicate variables aren’t created. The function can modify the variable’s value directly. Any modifications to the variable in the function affect the variable here in this scope too.

void function_name(int *x)
{
    ...
}

In C++, you can pass a variable by reference by passing in a variable, and defining the function’s parameter like int &x. Any modifications to the variable inside the function will also affect the variable here in this scope too.

void function_name(int &x)
{
    ...
}

Which to use is a matter of style, and whether you want to perform pointer arithmetic in the function. Google has specific guidelines for which to use where.

  • References

  1. C++ : Understanding pointers

你可能感兴趣的:(#,C,C++,Cython,pointer,指针)