gpt4 book ai didi

c - 使用&a和a有什么区别

转载 作者:行者123 更新时间:2023-11-30 21:35:11 24 4
gpt4 key购买 nike

读取数字到&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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com