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.

2
  • 4
    fruittable + i*sizeof(t_fruitdata) -> fruittable + i. Pointer arithmetics. Commented Jul 26, 2018 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. Commented Jul 26, 2018 at 20:27

1 Answer 1

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++;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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). See also: See What should main() return in C and C++?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.