我想探索一下,如果将值传递给指针的地址而不事先声明地址本身,会发生什么。声明后,我将 a
的地址指定为指针本身的值。当我现在打印 a
的值时,无论我是否更改数据类型或 *ptr
的值,我总是会得到 8
作为输出>。为什么?
#include<stdio.h>
int main(){
int a, *ptr = 190;
ptr = &a;
printf(%d, a);
return 0;
}
输出: 8
小修正:数据类型确实很重要,对于 char 和 Short,我总是得到 0
。对于 int
、long int
等,我总是得到 8
。使用double
,我得到4200624
。还是很困惑。
最佳答案
int a, *ptr = 190;
通常必须在编译时至少抛出警告,因为您尝试分配 int
值来初始化指针。在我的编译器上我得到:
a.c:3:11: warning: incompatible integer to pointer conversion initializing
'int *' with an expression of type 'int' [-Wint-conversion]
int a, *ptr = 190;
^ ~~~
这可能不是您想要的,为指针分配固定值是非常具体的用法。
printf(%d, a);
是一个错误,因为 printf
第一个参数必须是 char *
。您可能想编写printf("%d"...)
。我的编译器说:
a.c:5:10: error: expected expression
printf(%d, a);
^
即使在这种情况下,整个程序也是未定义的行为,因为您试图通过指针ptr
读取一个变量(a
)之前没有分配过。
你可能想写这样的东西:
#include<stdio.h>
int main(){
int a, *ptr;// definition of two variables, one of type int, one of type pointer to int, both non initialized
ptr = &a; // ptr points to variable a (contains its address)
*ptr = 190; // assignment of the variable pointed by ptr
printf("%d\n", a); // should print 190 as the content of a has been previously assigned
return 0;
}
关于c - 刚刚在 C 中尝试了简单的指针,但很令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487054/