Language C Functional dynamic memory

1

I want to reserve memory for a dynamic variable and assign value in the same function to avoid duplicating code, but I can not make the value take it in the main, it only remains in the function. Thank you very much

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

void creadin(int *);

int main() {

    int *a,*b,*c;
    creadin(a); //no pongo ampersand porque al ser puntero ya es una direccion de memoria por lo cual deberia ser modificada

    creadin(b);
    creadin(c);
    return 0;
}

void creadin(int *a){

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

  scanf("%d", &(*a));

  }
    
asked by Franco Rolando 24.12.2017 в 21:55
source

1 answer

2
  

// I do not put ampersand because being a pointer is already a memory address so it should be modified

Incorrect. If you want to modify anything external to your function that is not global in scope , you have to use a pointer **.

...
creadin(&a);

Void creadin(int **a){
  *a = (int *) malloc(sizeof(int));
  scanf("%d", *a);
}
    
answered by 25.12.2017 / 01:03
source