George Hilliard
George Hilliard

Reputation: 15952

Cleaning up pointers in C code

In the following code snippet, what can be done to a) hush the compiler, and b) clean up the eye-crossing pointer mess?

extern struct tree *sintablein[sintablesize];
struct tree *(*tablein)[];
int i;

tablein = &sintablein;     // The compiler complains:
                           // "redundant & applied to array (warning)" and
                           // "illegal conversion between pointer types (warning)"

for(i = 0; i < 10; i++) {
    struct tree *tablemember = (*tablein)[i];   // However, this works like a charm.
    // Do stuff with tablemember
}

The only way I was able to get this far was with the very helpful http://cdecl.org/. In particular regarding (b), how can I simplify the pointers and dereferences as much as possible?

Upvotes: 0

Views: 497

Answers (2)

paddy
paddy

Reputation: 63481

I would do it like this:

extern struct tree *sintablein[sintablesize];
struct tree **tablein = sintablein;

// ...

for(i = 0; i < 10; i++) {
    struct tree *tablemember = tablein[i];
    // Do stuff with tablemember
}

Note that when you did (*tablein)[i] you were taking the first element of the tablein array and treating it as an array of struct tree items instead of a single struct tree* pointer. That's probably not what you intended.

Upvotes: 1

RonaldBarzell
RonaldBarzell

Reputation: 3830

The best way to hush the compiler is to heed its advice. If a compiler complains, then there's usually a good reason for it. Even if the code works, there's a chance that it could cause problems in the future or on another platform.

Now, having said that, two ways to hush a compiler are:

  1. Adjust the warning sensitivity.
  2. Use casting (often the complaints can be resolved by an explicit cast).

As for the eye-crossing pointer mess... you'll have to be more specific. If you're dealing with C, you're pretty much going to be dealing with pointers, and sometimes eye-crossing is exactly what you'll end up with :)

Upvotes: 1

Related Questions