Search code examples
cpointersstructabstract-data-type

Why am I using x->y = z instead of x.y = z in my C code?


I'm following instructions to create code for a flexible array, and I am told to use x->y = z instead of x.y = z. What would be the reason to use pointers instead of just assigning values normally?

This code includes a custom library flexarray.h which I'll put at the bottom

flexarray.c:

struct flexarrayrec{
   int capacity;
   int itemcount;
   int *items;
};

flexarray flexarray_new(){
   flexarray result = emalloc(sizeof *result);
   result->capacity = 2;
   result->itemcount = 0;
   result->items = emalloc(result->capacity * sizeof result->items[0]);
   return result;
}

flexarray.h:

#ifndef FLEXARRAY_H_
#define FLEXARRAY_H_

typedef struct flexarrayrec *flexarray;

extern void flexarray_append(flexarray f, int item);
extern void flexarray_free(flexarray f);
extern flexarray flexarray_new();
extern void flexarray_print(flexarray f);
extern void flexarray_sort(flexarray f);

#endif

Solution

  • x->y is just syntax sugar for this

    (*x).y
    

    Looks like flexarray is just typedef for *flexarrayrec, so when you write flexarray result, compiler will "transform" it to

    flexarrayrec *result = emalloc(sizeof(flexarrayrec));
    

    So result.capacity, for example, would have no meaning as pointer is just a number (memory address), "it doesn't have any field". (*result).capacity will work, but it's frustrating to write so many asterisks and parentheses, that's why we use -> operator :)