Question

I'm sure this is a brain fart, but I'm missing something and a google search doesn't seem to be bringing up anything.

struct item
{
   int a;
   int b;
   int c;
};

typedef item *itemcatalog;

So 'itemcatalog' is simply an array of 'item's.

const item items[] = {{1,2,3},{4,5,6}};

const item *collection = items; // OK
const itemcatalog catalog = items; // "item const *" is incompatible with "itemcatalog"

The idea is that "itemcatalog" is more descriptive and shows that an array of items is expected rather than just a pointer to a single item.

EDIT: fix typo.

Was it helpful?

Solution

First, there's a typo:

On the line that fails, you have forgotten to name the object.

const itemcatalog collection2 = items;

Now, let's also try to apply const qualifiers to these variables:

When we do this, we still get an error:

foo.cc:14:19: error: cannot initialize a variable of type 'const itemcatalog' (aka 'item *const') with an lvalue of type 'const item [2]'
const itemcatalog catalog = items;
                  ^         ~~~~~
1 error generated.

To fix this, we need to realize that we actually need two typedefs in this situation:

struct item
{
    int a;
    int b;
    int c;
};

typedef item *itemcatalog;
typedef const item *constitemcatalog;

const item items[] = {{1,2,3},{4,5,6}};

const item *collection = items;
const constitemcatalog collection2 = items;

item mutable_items[] = {{1,2,3},{4,5,6}};

const item *collection3 = mutable_items;
const itemcatalog collection4 = mutable_items;

On the various collection objects, the const we are applying tells us if we can move the pointer. constitemcatalog vs itemcatalog tells us if we can modify the data the pointer points to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top