1

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.

5
  • 2
    try: itemcatalog t = items; or itemcatalog collection2 = items; Commented Apr 7, 2014 at 13:55
  • 1
    If you want to learn something to use in your professional programming, a standard container is superior in every relevant aspect. Commented Apr 7, 2014 at 13:57
  • I don't think a standard container can be used as there is no heap memory available (embedded platform), so things like vector would fail. Commented Apr 7, 2014 at 14:03
  • @squidge: You could use std::array, but I wouldn't fault you for not using it on a low memory board. Commented Apr 7, 2014 at 14:04
  • I prefer to not have a typedef in cases like this. It might make sense if it is std::map<X, <std:vector<Y> > or something harder to "get right", but in this case, no. Commented Apr 7, 2014 at 14:06

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice description and explanation, thanks :) Accepted and voted up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.