再谈C语言中的指针~~
General syntax
datatype *var_name;使用指针时,必须明白两个符号
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
// The output of this program can be different
// in different runs. Note that the program
// prints address of a variable and a variable
// can be assigned different address in different
// runs.
#include <stdio.h>
int main()
{
int x;
// Prints address of x
printf("%p", &x);
return 0;
}One more operator is unary * (Asterisk) which is used for two things:
声明指针
// C program to demonstrate declaration of // pointer variables. #include <stdio.h> int main() { int x = 10; // 1) Since there is * in declaration, ptr // becomes a pointer variable (a variable // that stores address of another variable) // 2) Since there is int before *, ptr is // pointer to an integer type variable int *ptr; // & operator before x is used to get address // of x. The address of x is assigned to ptr. ptr = &x; return 0; }访问储存在该地址的值
// C program to demonstrate use of * for pointers in C #include <stdio.h> int main() { // A normal integer variable int Var = 10; // A pointer variable that holds address of var. int *ptr = &Var; // This line prints value at address stored in ptr. // Value stored is value of variable "var" printf("Value of Var = %d\n", *ptr); // The output of this line may be different in different // runs even on same machine. printf("Address of Var = %p\n", ptr); // We can also use ptr as lvalue (Left hand // side of assignment) *ptr = 20; // Value at address is now 20 // This prints 20 printf("After doing *ptr = 20, *ptr is %d\n", *ptr); return 0; }
Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers. A pointer may be:
- incremented ( ++ )
- decremented ( — )
- an integer may be added to a pointer ( + or += )
- an integer may be subtracted from a pointer ( – or -= )
Pointer arithmetic is meaningless unless performed on an array.
Note : Pointers contain addresses. Adding two addresses makes no sense, because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between these two addresses.
unary operator称为一元运算符,一元运算符只需要一个运算对象,例如,36-12,这个是二元,因为有两个运算对象;而-16是一元,只有一个运算对象。
参考资料:
Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
评论已关闭