学习C语言中指针

2018-04-24  本文已影响0人  obsession_me

这里的话给出一堆例子,既可以很好的理解C语言中取值(*)和取址(&)的运用了。

#include <stdio.h>

int main(){
    int a, *b;
    a = 1;
    b = &a;
    
    printf("the value of a is: %d\n", a);
    printf("the value of b is: %d\n", b);
    
    return 0;
}

输出为:

the value of a is: 1
the value of b is: 49694020

当我们将输出语句修改为如下的形式时:

    printf("the value of a is: %d\n", *a);
    printf("the value of b is: %d\n", *b);

这个时候,gcc编译器会弹出错误:

main.c: In function ‘main’:
main.c:8:39: error: invalid type argument of unary ‘*’ (have ‘int’)
     printf("the value of a is: %d\n", *a);
                                       ^~

从上面可以看到,编译器弹出错误提示我们不能再变量a前面加“*”
因此,我们尝试将这个“*”去除再编译运行一下:

    printf("the value of a is: %d\n", a);
    printf("the value of b is: %d\n", *b);

输出为:

the value of a is: 1
the value of b is: 1

接下来,我们尝试取址符号的使用

    printf("the value of a is: %p\n", &a);
    printf("the value of b is: %p\n", &b);

可以得到如下输出

the value of a is: 0x7ffcf83041bc
the value of b is: 0x7ffcf83041b0

明显可以看出,这两个值是不一样的,于是我们就在想,为什么这个会不一样呢,接下来我们继续更改输出的形式:

    printf("the value of a is: %p\n", &a);
    printf("the value of b is: %p\n", b);

输出如下:

the value of a is: 0x7ffcf83041bc
the value of b is: 0x7ffcf83041bc

这里就可以明显的观察到两者的地址是相同的
接下来我们考虑一个更为复杂的情况:

    printf("the value of a is: %p\n", &a);
    printf("the value of b is: %p\n", *(&b));

输出如下:

the value of a is: 0x7ffcf83041bc
the value of b is: 0x7ffcf83041bc
- * & *(&)
a error a的地址 1
b 1 b的地址 a的地址

如此,我们可以使用一个表格来总结一下之前的情况a=1,*b=&a;

- * & *(&)
a error a的地址 1
b 1 b的地址 a的地址

这个编辑器让我有点迷


捕获.PNG

其实说到了这里,我们大概对于这两个符号的使用就非常得心应手了,很简单的,我们可以理解*为取后面变量的值,而&就是取后面变量的地址,如果&后面是指针变量,即取得就是指针变量的地址,也可以理解为变量的地址的地址。

上一篇下一篇

猜你喜欢

热点阅读