:: Re: [DNG] Making sense of C pointer…
Página superior
Eliminar este mensaje
Responder a este mensaje
Autor: karl
Fecha:  
A: dng
Asunto: Re: [DNG] Making sense of C pointer syntax.
Edward Bartolo:
...
> However, C pointer syntax is proving to be as unintuitive as it can
> be.

...
> I want to understand, as opposed to knowing by rote, the
> mechanism why they work.

...

///

I think one source of confusion re. c-pointers is that they are
declared "as they are used", but you migth not use them like that.

If you take

int *ix;

then *ix will be an int, and you can _deduce_ that ix is a pointer to
an int, but you don't say that directly. In your code you try to avoid
the issue by writing "int* i;" and treating "int*" to be a "pointer"
declaration. But "int * i ;" is four tokens regardless how you write it,
you could just as well have written it as "int*i;" or "int *i;", same thing.

To exemplify the "as they are used" statement, take a function pointer
declaration:

void (*log_func)(int priority, const char *format);

here you cannot conveniently move the "*" to the "void" so it will look
like a "pointer" declaration; it declares log_func to be something which
if used as (*log_func)(a, b, d) will "give" you a void value.

///

There is also a visual mismatch in c with a declaration of a pointer
with an initializer. Example:

int *ix = (int *) malloc(sizeof(int));

This line is the same thing as

int *ix; /* i.e. *ix is an int */
ix = (int *) malloc(sizeof(int)); /* look no "*" */

So, int *ix = value; says two things;

a: it declares an "ix" such as when ix is used as "*ix" it will be an int
b: ix = value

Another example is:

#include <syslog.h>
#include <stdarg.h>

void (*log_vfunc)(int priority, const char *format, va_list ap) = vsyslog;

where the last line is the same thing as:

void (*log_vfunc)(int priority, const char *format, va_list ap);
log_vfunc = vsyslog;

Regards,
/Karl Hammar

-----------------------------------------------------------------------
Aspö Data
Lilla Aspö 148
S-742 94 Östhammar
Sweden
+46 173 140 57