我有这个简单的程序:
#include <stdio.h>
struct time
{
int hours ;
int minutes ;
int seconds ;
} t[2] = {1,2,3,4,5,6};
int main() {
struct time *tt = t;
printf("%d\n", (*tt));
printf("%d", *(tt+1));
}
现在预期的输出应该是:
1
4
但我得到的输出是 2 个完全相同的内存地址。我将这个程序发送给其他人,有些人有预期的输出,但有些人没有。我认为这是 C 或 GCC 版本的问题。它可以解决吗?是否有关于为什么在我的 C 版本中发生这种情况的任何解释?
最奇怪的是,即使在我取消引用指针之后,它仍然会打印一些地址。这怎么可能?
另一方面,如果我将程序更改为:
$include <stdio.h>
struct time
{
int hours ;
int minutes ;
int seconds ;
} t[2] = {1,2,3,4,5,6};
int main() {
struct time *tt = t;
printf("%d\n", (*tt).hours);
printf("%d", (*(tt+1)).hours);
}
它打印出预期的输出。
这种行为的解释是什么?谢谢。
最佳答案
问题不在编译器,而是你对C的理解。让我们用GCC version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)编译:
% gcc struct_time.c
struct_time.c: In function ‘main’:
struct_time.c:12:14: warning: format ‘%d’ expects argument of type ‘int’,
but argument 2 has type ‘struct time’ [-Wformat=]
printf("%d\n", (*tt));
~^ ~~~~~
struct_time.c:13:14: warning: format ‘%d’ expects argument of type ‘int’,
but argument 2 has type ‘struct time’ [-Wformat=]
printf("%d", *(tt+1));
~^ ~~~~~~~
您的格式是 %d
,它需要一个 int
作为相应的参数,并且您正在传递 struct time
。程序的行为是未定义的,因为转换说明符与实际参数的类型不匹配。
值在内存中的位置并不重要——它们的类型也很重要。尽管 tt[0]
的地址与 tt[0].hours
相同,但它们具有不同的类型。在一个中你想要整个结构,在另一个中你想要包含在第一个成员中的值。
关于c - 结构指针 - 使用指针访问结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801752/