Home >Backend Development >C++ >The difference between * and & in C language

The difference between * and & in C language

下次还敢
下次还敢Original
2024-04-27 22:51:15683browse

In C language, (asterisk) is used for indirect addressing and value, while & (address character) is used for address and reference. Get the value pointed to by the variable or pointer, used to modify the value and declare the pointer variable; & Get the variable address, used to assign the address to the pointer variable and pass the address as a function parameter.

The difference between * and & in C language

The difference between * and & in C language

The symbols * and & are different operations in C language Symbols, used for different purposes:

Meaning:

  • Asterisk *: indicates indirect addressing or pointer value operation symbol.
  • Address character &: represents the address or reference operator.

Purpose:

Asterisk*:

  • Get the variable or the variable pointed to by the pointer value.
  • Modify the value of a variable or a variable pointed to by a pointer.
  • As part of the declaration of the pointer variable.

Address symbol &:

  • Get the address (memory location) of the variable.
  • Assign the address of the variable to the pointer variable.
  • Pass the address of the variable as a function parameter.

Example:

int main() {
    int x = 10;
    int *ptr = &x;  // ptr指向x的地址

    // 获取x的值
    printf("x = %d\n", x);

    // 使用指针获取x的值
    printf("*ptr = %d\n", *ptr);

    // 使用指针修改x的值
    *ptr = 20;
    printf("x = %d\n", x);  // x的值已经改变为20

    return 0;
}

Note:

  • *ptr represents the variable pointed to by the pointer variable ptr The value of , and &x represents the address of variable x.
  • Normally, a pointer variable is a variable of type "variable type*", pointing to a variable of a specific type.
  • Address-taking and indirect addressing operators can be used in combination to implement pointer arithmetic and other advanced data structures.

The above is the detailed content of The difference between * 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