无法通过指针索引访问结构数组成员

时间:2018-07-26 19:39:30

标签: c arrays struct pointer-arithmetic

我正在尝试从全局结构数组访问数据。但是,以下应用程序崩溃。

#include <stdio.h>

typedef struct {
    char *fruit;
    int score;
} t_fruitdata;

static t_fruitdata fruittable[] = {
    {"Apple", 100},
    {"Banana", 240},
    {"Carrot", 40}
};

void main()
{
    int table_len = sizeof(fruittable) / sizeof(t_fruitdata);
    for (int i = 0; i < table_len; ++i)
    {
        t_fruitdata *fruitdata = fruittable + i*sizeof(t_fruitdata);
        printf("At index %i fruit %s has a score of %i\n",
            i,
            fruitdata->fruit,
            fruitdata->score);
    }
}

输出:

At index 0 fruit Apple has a score of 100
[program terminates here]

我想我偶然发现了一些未定义的行为?但是我之前已经看过推荐在堆栈溢出时使用的这项技术。我在Windows上使用cl将其与Visual Code 2017一起编译。

1 个答案:

答案 0 :(得分:1)

t_fruitdata *fruitdata = fruittable + i*sizeof(t_fruitdata);中,您没有正确地增加指针。

#include <stdio.h>

typedef struct {
    char *fruit;
    int score;
} t_fruitdata;

static t_fruitdata fruittable[] = {
    {"Apple", 100},
    {"Banana", 240},
    {"Carrot", 40}
};

void main()
{
    int table_len = sizeof(fruittable) / sizeof(t_fruitdata);
  t_fruitdata *fruitdata = fruittable;

    for (int i = 0; i < table_len; ++i)
    {
           printf("At index %i fruit %s has a score of %i\n",
            i,
            fruitdata->fruit,
            fruitdata->score);
fruitdata++;
    }
}