c - 结构指针 - 使用指针访问结构数组

标签 c pointers struct

我有这个简单的程序:

#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/

相关文章:

c - 如何使用指向切片字符串的指针的指针

c - 试图修复有关 ‘const’ 限定符的警告

c - 结构有什么特别之处?

c - 警告 : assignment from incompatible pointer type (Pointers and structures)

c - 在C中创建while循环的问题

c - 在 for 循环比较中使用二进制数

c++ - 不知道这个指针可能指向什么并且无法解释结果

C++ 在结构 vector 上使用 std::transform

c - 共享内存段 shmget shmat 双访问两者

c - 返回 char 数组的 C 函数与使用 2 个 char 数组的函数