简体   繁体   中英

Dynamic allocation example in C

What is going on with adress and pointer types. Can we dealocate the momory in the main function.

int *read(int *n) {
  int i, *niz;
  do { 
    printf("n="); 
    scanf("%d", n);
  } while (*n < 1);
  
  niz = (int *)malloc(*n * sizeof(int));
  
  for (i = 0; i < *n; i++) { 
    printf("%d. broj: ", i + 1);
    scanf("%d", niz + i); 
  }

  return niz;
}

int main() {
  int i, n, *niz;
  niz = read(&n); 
  printf("Niz:");
  
  for (i = 0; i < n; i++)
    printf(" %d", niz[i]);
  
  free(niz);
  return 0;
}

I don't understand why do we need a function pointer (*read), and why do we need the pointer in the read function while using n?

To make it clear you may rewrite the function declaration

int *read(int *n) {

the following way

int * ( read(int *n) ){

That is it is a function that has one parameter with the name n of the type int * and the return type int * .

In main the variable n declared like

int i, n, *niz;

is passed to the function read by reference through a pointer to it

niz = read(&n);

because we want that the variable would get a value assigned in the function. So dereferencing the pointer the function will have a direct access to the original variable n declared in main and can change its value.

This value assigned in the function read to the original variable n declared in main through a pointer to it is used in main in this for loop

for (i = 0; i < n; i++)
  printf(" %d", niz[i]);

Otherwise if the function would be declared like

int * ( read(int n) ){

and called like

niz = read(n);

then the function would deal with a copy of the value of the variable n declared in main. Changing the copy of the value of the variable n within the function leaves the value of the original variable n declared in main unchanged. It is the copy of the value that would be changed not the original variable itself.

Pay attention to that the returned pointer from the function points to a dynamically allocated memory. So using the pointer in main you can free the allocated memory within the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM