F
F
Facepunch2020-12-10 04:05:40
C++ / C#
Facepunch, 2020-12-10 04:05:40

How to implement memory allocation (malloc) through a function?

I can't figure out how to implement memory allocation through a function. I passed the pointer, but what to do with it is not clear.

void Test(int *a){
  *a = (int*)malloc(1 * sizeof(int));
}
int main(){
  int *a = NULL;
  setlocale(LC_ALL, "Russian");
  //a = (int*)malloc(1 * sizeof(int));
  Test(a);
  if (a==NULL){
    printf("\nМассива нет!");
  } else printf ("\nМассив есть!");
  free(a);
  getch();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
CityCat4, 2020-12-10
@Facepunch

To change the value of the passed element, you need to pass a pointer to it - in this case, pass a pointer to a pointer :)

A
Alexander Ananiev, 2020-12-10
@SaNNy32

int* test()
{
   return (int*)malloc(1 * sizeof(int));
}

A
avocore, 2020-12-10
@avocore

In order to change the value of a variable in another function (in our case, the address is small), you need to pass the address to it, i.e. pointer to pointer.
Test(&a);
And in the Test() function, add * and &, or work with a double pointer through a variable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question