我现在在学C,这几天在研究指针,正好带着一道题来!
int *ptr; //declare the ptr
ptr = &var; //init the ptr with the address of the variable var
通过这些行,我创建了一个指针,并将 ptr 与一个变量链接起来。我的问题是,当我声明一个指针 int *ptr;
并且我没有用地址初始化它时,这个指针指向哪里?
最佳答案
在 C 中,变量通常不会被初始化,除非你特别说明:
int a; // not initialized
int b = 1; // initialized
int arr[10]; // not initialized
int brr[4] = { 1 }; // initialized as { 1, 0, 0, 0 }
void * p; // not initialized
void * q = &a; // initialized
(静态或线程本地存储的变量有异常(exception),它们总是零初始化。)
不允许尝试获取未初始化变量的值。对于未初始化的变量,你唯一能做的就是给它赋值,这不会访问它的当前值,而只会给它赋一个新值。在初始化或赋值之前,变量的当前值是“不确定的”,您不能尝试访问它。这样做会导致未定义的行为。
这对所有 变量都是正确的,但尤其适用于您的指针变量。在您分配一个值之前,它没有任何有意义的值。
void * p; // not initialized
if (p) { /*...*/ } // undefined behaviour!
printf("%p\n", p); // undefined behaviour!
p = &a; // now p has a well-defined value
导致未定义行为的操作的技术术语是所谓的“左值转换”。那是您获取命名变量(“左值”)并使用其内容的时刻。例如。 C11,6.3.2.1/2 说:
If the lvalue designates an object of automatic storage duration [...] and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
关于c - 一个新声明的指针,它指向哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19621112/