简体   繁体   English

引用C结构而不引用成员

[英]Referencing C struct without referencing a member

typedef struct s {
  int x;
  int y;
} S;

typedef struct t {
  S s;
}

T t = {0};
T *pointer_to_T = &t;


printf("End address %x", pointer_to_T->s);
printf("Beginning address %x", &(pointer_to_T->s));

Based on my testing, pointer_to_T->s is the address of the end of the structure S 根据我的测试,pointer_to_T-> s是结构S末端的地址

pointer_to_T->s - &(pointer_to_T->s) = sizeof(S)

What is the expected behaviour here? 这里的预期行为是什么? Or is this just a coincidence? 还是只是巧合?

The expected behaviour here can range from printing garbage to nasal demons , because this behaviour is undefined. 此处的预期行为可能范围从打印垃圾到鼻恶魔 ,因为此行为是未定义的。 The %x specifier makes printf expect an integer but it gets a struct, so anything is possible. %x说明符使printf期望一个整数,但它得到一个结构,因此一切皆有可能。 What's most likely happening here is that it would print sx , but again it may as well spawn a one-way portal to Петропа́вловск-Камча́тский . 这里最有可能发生的事情是它将打印sx ,但同样可能会产生一个单向的Петропа́вловск-Камча́тский门户。

Structures element isnot a pointer. 结构元素不是指针。 It won't print any address of the structure. 它不会打印该结构的任何地址。 That would be just garbage value which you are considering as end address. 那只是您正在考虑作为结束地址的垃圾值。 Garbage is undefined. 垃圾是未定义的。

Structure elements are not pointer that way array is. 结构元素不是数组的指针。

%x – Print a hexadecimal integer %x –打印一个十六进制整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM