c - 结构数组指针

标签 c loops pointers struct

好的,我有这个代码:

#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 5

struct mys
{
    double first;
    unsigned long second;
    char str[10];
};

int main(int argc, char** argv)
{
    size_t i = 0;
    struct mys thes[ARR_SIZE] = 
        {
            {1.1, 1, "First"},
            {2.2, 2, "Second"},
            {3.3, 3, "Third"},
            {4.4, 4, "Fourth"},
            {5.5, 5, "Fifth"}
        };//load array of structures with values

    for (; i < ARR_SIZE; ++i)
        fprintf(stdout, "second->%lu\n", thes[i].second);//loop through array thes and print element second

    return (EXIT_SUCCESS);
}

现在,我想获取第 0 个元素 thes 中名为 second 的元素的地址,然后使用它遍历数组 thes 并打印每个第二个元素。

#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 5

struct mys
{
    double first;
    unsigned long second;
    char str[10];
};

int main(int argc, char** argv)
{
    size_t i = 0;
    unsigned long * ptr = NULL;//pointer to unsigned long
    struct mys thes[ARR_SIZE] = 
        {
            {1.1, 1, "First"},
            {2.2, 2, "Second"},
            {3.3, 3, "Third"},
            {4.4, 4, "Fourth"},
            {5.5, 5, "Fifth"}
        };

    //first loop
    for (; i < ARR_SIZE; ++i)
        fprintf(stdout, "second->%lu\n", thes[i].second);

    ptr = &thes[0].second;//get the address of the second element of the zero'th array structure and store it in ptr

    // Now I want to use the above pointer ptr to loop through the array thes and display the second element like I did above, but I can't manage to do that.
    //The output of this loop should be the same as the first loop 

    return (EXIT_SUCCESS);
}

所以,我已经实现了指针,但是我在为第二个循环编写代码时遇到了问题。感谢您的帮助。

最佳答案

for (; i < ARR_SIZE; ++i)
    fprintf(stdout, "second->%lu\n", *( unsigned long * )(( char * )ptr + i * sizeof( struct mys ) ));

关于c - 结构数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20654851/

相关文章:

c - (C) strtok 具有多个空格/制表符,用指针检查 null

c 数组分配不正确

c++ - 为什么 NULL 指针在 C 和 C++ 中的定义不同?

c - foo() 的用例是什么(意味着 foo 有未知数量的参数)?

c - Linux 中 MMAP 值的生命周期

python - 矩阵程序,使用python中的绑定(bind)来停止/启动

java - java中是否有类似 "trim"的方法用于整数循环?

c - 理解c语言中的基本变量声明

c - C中用指针替换下标

javascript - 使用全局标志将字符串文字作为 Javascript .replace() 模式传递