Home >Backend Development >C++ >Detailed explanation of the difference and usage of * and & in C language

Detailed explanation of the difference and usage of * and & in C language

王林
王林Original
2024-04-03 18:12:011137browse

In C language, it is used to dereference a pointer and return the value pointed to; & is used to take an address and return a pointer to the variable. Typically used to access or modify the value pointed to by a pointer; & is typically used to create a pointer or pass a reference.

Detailed explanation of the difference and usage of * and & in C language

Detailed explanation of the difference and usage of * and & in C language

In C language, *## There are important differences between the # and & operators that work with pointers.

Operator*(Dereference)

  • * Operator is used to dereference a pointer and return The value pointed to by the pointer.
  • Syntax:
  • *ptr, where ptr is a pointer to a variable.

Example:

int *ptr;
int value = 10;
ptr = &value; // 为 ptr 分配 value 的地址
*ptr = 20; // 将 value 的值修改为 20

Operator&(get address)

  • & The operator is used to take the address of a variable and return a pointer to the variable.
  • Syntax:
  • &var, where var is a variable.

Example:

int value = 10;
int *ptr = &value; // 为 ptr 分配 value 的地址

Difference

  • * Dereference pointer, & get variable address.
  • * returns the value pointed to, & returns a pointer to the value.
  • & is typically used when creating a pointer variable or passing a reference as a function parameter.
  • #* is usually used when accessing or modifying the value pointed to by a pointer.

Practical case

The following is a practical case using the

* and & operators :

#include <stdio.h>

int main() {
    int value = 10;
    int *ptr = &value; // 为 ptr 分配 value 的地址

    // 使用 * 解引用指针并打印值
    printf("Value: %d\n", *ptr);

    // 使用 * 修改指针所指向的值
    *ptr = 20;

    // 再次使用 * 打印修改后的值
    printf("Modified value: %d\n", *ptr);

    return 0;
}

Output:

Value: 10
Modified value: 20

The above is the detailed content of Detailed explanation of the difference and usage 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