c语言中指针怎么去学,学习C语言中指针

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

#include

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的地址

这个编辑器让我有点迷

c92848493763

捕获.PNG

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值