作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
读取数字到&a
和读取a
有什么区别
int main(int argc, char** argv) {
int a;
printf("A:");
scanf("%d",&a);
printf("Address:%p\n",&a);
printf("value A:%d",a);
return (0);
}
有时我看到代码不是读取变量,而是读取地址,我知道变量只是内存,但不一样?我可以两者都做吗?或者有时我必须特别使用其中之一?
最佳答案
在 C 语言中,如果您希望函数修改对象的值(例如 scanf
调用中的 a
),则必须传递一个指针到该对象。指针是计算结果为内存中对象位置的任何表达式。在本例中,指向 a
的指针是通过使用一元 &
运算符获得的:
scanf( "%d", &a ); // write an integer value to a
您可以创建一个具有相同目的的指针变量:
int a;
int *p = &a; // the object p stores the location of a
// p points to a
scanf( "%d", p ); // also writes an integer value to a through the pointer p
// note no & here because p is already a pointer type
如果您只想将对象的值传递给函数,则不会使用 &
运算符:
printf( "%d", a ); // write the value stored in a to standard output,
// formatted as a decimal integer
如果您有一个指针,并且想要指针指向的值,则可以使用一元 *
运算符:
printf( "%d", *p ); // write the value stored in a to standard output,
// going through the pointer p
总结一下,
p == &a // int * == int *
*p == a // int == int
关于c - 使用&a和a有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43747898/
我是一名优秀的程序员,十分优秀!