:: Re: [DNG] Making sense of C pointer…
Forside
Slet denne besked
Besvar denne besked
Skribent: Rainer Weikusat
Dato:  
Til: dng
Emne: Re: [DNG] Making sense of C pointer syntax.
Edward Bartolo <edbarx@???> writes:
> As the title of the email indicates, I am doing some exercises to make
> sense out of C pointer syntax. I have been using pointers for as long
> as I have been programming without issues, apart from the usual
> initial programmatic errors when new code is run for the first time.
> However, C pointer syntax is proving to be as unintuitive as it can
> be. For this reason, I am doing some exercises regarding C pointer
> use.


[...]


> #include <stdio.h>
>
> void change_value(void* ptr) {
> *((int*) ptr) = 20000000;
> }


You could have declared that as int *ptr in order to get rid of the
cast. Also, the precedence is such that

*(int *)p = 20000000;

would work.


[...]

> #include <stdio.h>
> #include <stdlib.h>
>
> void change_value(void** ptr) {


This is a somewhat dubious construct as every pointer is required to be
convertible from and to void * but not void **.


> int* i = (int*) malloc(sizeof(int));


The cast is not necessary. And you don't really need the intermediate
pointer.

-------
#include <stdio.h>
#include <stdlib.h>

void change_value(int **ptr) {
    *ptr = malloc(sizeof(**ptr));
    **ptr = 10001002;
}


int main() {
int* p;

change_value(&p);
printf("p = %d\n", *p);
free(p);
    
    return 0;
}
------


This becomes much less arcane-looking when letting go of the Pascal-y
'bad habit' of using pass-by-reference to create procedure returning
values.

------
#include <stdio.h>
#include <stdlib.h>

int *array_1(void)
{
    int *pi;


    pi = malloc(sizeof(*pi));
    *pi = 10001002;


    return pi;
}


int main() {
int* p;

p = array_1();
printf("p = %d\n", *p);
free(p);
    
    return 0;
}
------


One thing to note here: Every C pointer is really a pointer to an array
of values, although the size of the array may just be one. Given the
above, both *p and p[0] are equally legitimate ways to access the
value. As per C definition, p[0] can also be written as 0[p] or *(p + 0)
the same being true for any other valid (not out-of-bounds) index.