:: [DNG] Making sense of C pointer syn…
Página Inicial
Delete this message
Reply to this message
Autor: Edward Bartolo
Data:  
Para: dng
Assunto: [DNG] Making sense of C pointer syntax.
Hi,

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.

I am attaching two short C programs that I created and which I tested
to work although the mechanism by which they work is still somewhat
hazy to me. Both programs use a function to change the value of a
parameter. I want to understand, as opposed to knowing by rote, the
mechanism why they work. Please note that I didn't consult any books
to create the pointers. This is because I have already the concepts,
but I cannot make sense, as in deeply understanding the details, of
pointer syntax as used in C.

Edward
#include <stdio.h>

void change_value(void* ptr) {
*((int*) ptr) = 20000000;
}

int main() {
  int p = 8;
  printf("p = %d\n", p);
  change_value(&p);
    printf("p = %d\n", p);

    
    return 0;
}
#include <stdio.h>
#include <stdlib.h>

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


int main() {
  int* p;
  //printf("p = %d\n", p);
  change_value((void**) &p);
    printf("p = %d\n", *p);
    free(p);

    
    return 0;
}