0

I am trying to accessing data from a global array of structs. However the following application crashes.

#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);
    }
}

Outputs:

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

I imagine I've stumbled into some undefined behavior? But I've seen this technique recommended on stack overflow before. I'm using cl on windows to compile this with Visual Code 2017.

curious-cat
  • 331
  • 1
  • 6
  • 17
  • 4
    `fruittable + i*sizeof(t_fruitdata)` -> `fruittable + i`. Pointer arithmetics. – Eugene Sh. Jul 26 '18 at 19:50
  • 1
    More specifically, `t_fruitdata *fruitdata = fruittable + i` treats `i` as an index of `t_fruitdata` structs, so in the statement I've written, i is automatically multiplied by `sizeof(t_fruitdata)` when evaluating where `fruitdata` points. This in turn means that you don't need to do the multiplication yourself. – dgnuff Jul 26 '18 at 20:27

1 Answers1

1

In t_fruitdata *fruitdata = fruittable + i*sizeof(t_fruitdata); you are not correctly incrementing the pointer.

#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++;
    }
}
John Bollinger
  • 121,924
  • 8
  • 64
  • 118
kiran Biradar
  • 12,116
  • 3
  • 14
  • 35
  • The proper declarations for `main` are `int main (void)` and `int main (int argc, char **argv)` (which you will see written with the equivalent `char *argv[]`). **note:** `main` is a function of `type int` and it returns a value. See: [C11 Standard §5.1.2.2.1 Program startup p1 (draft n1570)](http://port70.net/~nsz/c/c11/n1570.html#5.1.2.2.1p1). See also: [See What should main() return in C and C++?](http://stackoverflow.com/questions/204476/) – David C. Rankin Jul 26 '18 at 20:45
  • I'd rather use fruitdata[i] or (fruitdata + i) instead of fruitdata++ to avoid any mistakes since you are changing where the pointer fruitdata is pointing. – Murillo Ferreira Jul 26 '18 at 21:20