:: Re: [DNG] Making sense of C pointer…
Αρχική Σελίδα
Delete this message
Reply to this message
Συντάκτης: Edward Bartolo
Ημερομηνία:  
Προς: dng
Αντικείμενο: Re: [DNG] Making sense of C pointer syntax.
Hi,

Thanks for dedicating some of your time to answer me. I used:

void change_value(void** ptr)

Because I wanted to enable myself to allocate memory for the pointer
inside the function, therefore I needed a pointer to a pointer of type
void. Void allows such a function to handle different data types in
which case an ordinal typed parameter may be used to allow a switch
statement within the function to handle the different data types. I
used such a construct in Delphi Pascal in the past, and consider it a
powerful feature that can have its uses. This is why I am anxious to
comprehend the why behind pointer to pointer use.

This is a program employing the use of a pointer to change the value
of a parameter inside a function.

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

int afunc(double* dd) {
*dd *= 2;
}

int main() {
double* mm;
mm = malloc(sizeof(double));
printf("value of mm after creation, unassigned: %f\n", *mm);
*mm = 1.0;
    
  int j;
  for (j = 1; j <= 20; j++) {
    afunc(mm);
    printf("value of mm after function call %d: %f\n", j, *mm);
  }

    
free(mm);
    
return 0;
}

I will post tomorrow a reply illustrating the allocation of memory to
a pointer within a function. This means the function must be able to
modify the pointer not only its data. For that I will probably need a
pointer to a pointer or use typecasting with a standard data type
having the same number of bytes as a pointer. The reason for this is
the fact that a pointer is a number.

I found using the return value of a function makes code much more
readable and probably more reliable. Multiple return values can be
encapsulated inside a structure which would be returned by a function.
I used this construct in simple-netaid-lightweight which avoids the
use of GtkBuilder.

Edward