c - 刚刚在 C 中尝试了简单的指针,但很令人困惑

标签 c pointers

我想探索一下,如果将值传递给指针的地址而不事先声明地址本身,会发生什么。声明后,我将 a 的地址指定为指针本身的值。当我现在打印 a 的值时,无论我是否更改数据类型或 *ptr 的值,我总是会得到 8 作为输出>。为什么?

#include<stdio.h>
 int main(){
  int a, *ptr = 190;
  ptr = &a;
  printf(%d, a);
  return 0;
 }

输出: 8

小修正:数据类型确实很重要,对于 char 和 Short,我总是得到 0。对于 intlong 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/

相关文章:

c - 指针与 c 中的整数二维数组和字符串不同

c - 段错误,第一次使用二维数组

c - 指针是 "passed by value"?

c - 如何打印 uint32_t 和 uint16_t 变量的值?

C:全局、静态变量理解

c - 数独 3x3 框检查 C 中是否重复

c - gcc 的 __sync 和 __atomic 内在函数有什么区别

c - 如何检查字符串C中的空格?

那个函数参数真的可以是指向常量的指针吗?

c - 当用户不提供输入时,我得到 "Segmentation fault: 11"。当用户提供输入时,它可以正常工作。我怎样才能解决这个问题?