Home >Backend Development >C++ >Master the application scenarios and differences of * and & in C language

Master the application scenarios and differences of * and & in C language

WBOY
WBOYOriginal
2024-04-03 16:54:02833browse

Pointers (*) store variable addresses and are used to access and modify variable values. The address operator (&) gets the address of a variable, which can be assigned to a pointer or passed to a function. The difference is: pointers can be dereferenced, while address operators themselves cannot access variable values.

Master the application scenarios and differences of * and & in C language

Application scenarios and differences between pointers (*) and address operators (&) in C language

Pointers (*)

  • Declaration: Use the * symbol, followed by the variable name
  • Function: Store the address of the variable
  • Purpose:

    • Access and modify the value of the variable (by dereferencing)
    • Pass the variable The address (as a parameter of the function)
    • Implementing dynamic memory allocation

Address operator (&)

  • Declaration: Use the & symbol, preceded by the variable name
  • Function: Get the address of the variable
  • Purpose:

    • Assign the address of the variable to the pointer
    • Pass the address of the variable (as a function parameter)

Difference

  • The pointer points to the address of the variable, while the address operator gets the address of the variable.
  • Pointers can be dereferenced to access and modify the value of a variable, but the address operator itself cannot access the value of a variable.

Practical case

The following code example demonstrates the use of pointer and address operators in C language:

#include <stdio.h>

int main() {
    int x = 10;

    // 获取 x 的地址并将其赋值给指针 p
    int *p = &x;

    // 使用解引用运算符 * 访问和修改 x 的值
    *p += 5;

    // 打印修改后的 x 值
    printf("x: %d\n", x); // 输出:15

    // 传递 p 指针作为函数的参数
    myFunction(p);

    return 0;
}

void myFunction(int *ptr) {
    // 修改指向值的变量
    *ptr = 20;
}

In this example Medium:

  • #*p Dereference pointer p and access the pointed variable x.
  • Function myFunction receives a pointer to x p and modifies the value of x through *ptr.

The above is the detailed content of Master the application scenarios and differences of * and & in C language. 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