打印指针时行为怪异 [英] Strange behaviour when printing pointers

查看:168
本文介绍了打印指针时行为怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

#include <stdio.h>

typedef struct {
  int* arg1;
  int  arg2;
} data;

int main(int argc, char** argv) {
  data d;
  printf("arg1: %p | arg2: %d\n", d.arg1, d.arg2);
}

输出最终被该 d.arg1 不是 NULL D。 ARG2 0。例如:

The output ends up being that d.arg1 is not NULL and d.arg2 is 0. For example:

arg1: 0x7fff84b3d660 | arg2: 0

当我添加一个指向主,没有什么变化。然而,当我打印指针:

When I add a pointer to main, nothing changes. However, when I print that pointer:

#include <stdio.h>

typedef struct {
  int* arg1;
  int  arg2;
} data;

int main(int argc, char** argv) {
  data d;
  int* test;
  printf("arg1: %p | arg2: %d | test: %p\n", d.arg1, d.arg2, test);
}

输出总是导致:

arg1: (nil) | arg2: 4195264 | test: (nil)

为什么我遇到这种行为?我不知道如何打印另一个指针值改变不同的指针为NULL值。请注意,我现在用的编译器GCC 4.8.2。

Why am I experiencing this behaviour? I don't understand how printing another pointer value changes the value of a different pointer to NULL. Note that the compiler I am using is GCC 4.8.2.

推荐答案

您遇到此行为是因为你的程序调用的未定义行为即可。 D 在你的程序uinitialized因此其值为不确定这调用不确定的行为。

You are experiencing this behavior because your program invokes undefined behavior. d is uinitialized in your program and hence its value is indeterminate and this invokes undefined behavior.

C11 6.7.9初始化:

如果具有自动存储时间的对象没有明确初始化,它的价值是不确定的。

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

这个答案:

这是不确定的值的甚至比未指定的更不确定。这是不是一个未确定的值或重新presentation一个陷阱。陷阱再presentation是对于一些魔法值,如果你尝试将其分配到任何东西,结果在不确定的行为当中,标准的说话。这不必是实际值;大概想它最好的办法就是如果C有异常,陷阱重新presentation将是一个例外。例如,如果你声明 INT I; 在块,没有初始化,变量的初始值i 是不确定的,也就是说如果你尝试将此分配给初始化之前别的东西,这种行为是未定义,编译器有权尝试说恶魔出鼻子的帽子戏法。当然,在大多数情况下,编译器会做那么戏剧性的东西/好玩,喜欢它初始化为0或其他一些随机的有效值,但不管它做什么,你无权反对。

An indeterminate value even more unspecified than unspecified. It's either an unspecified value or a trap representation. A trap representation is standards-speak for some magic value which, if you try to assign it to anything, results in undefined behavior. This wouldn't have to be an actual value; probably the best way to think about it is "if C had exceptions, a trap representation would be an exception". For example, if you declare int i; in a block, without an initialization, the initial value of the variable i is indeterminate, meaning that if you try to assign this to something else before initializing it, the behavior is undefined, and the compiler is entitled to try the said demons-out-of-nose trick. Of course, in most cases, the compiler will do something less dramatic/fun, like initialize it to 0 or some other random valid value, but no matter what it does, you're not entitled to object.

这篇关于打印指针时行为怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆