How to allocate dynamic memory inside a function with C

2 Answers

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

int* f(int*);

int main()
{
    int n = 90;
    int* p;
    
    p = f(p); 
    n = *p;
    
    free(p);

    printf("n = %d", n);
    
    return 0;
}

int* f(int* p) {
    p = (int*)malloc(sizeof(int));
    *p = 320;
    
    return p; 
}




/*
run:

n = 320

*/

 



answered Jul 7, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

int* f(int**);

int main()
{
    int n = 90;
    int* p;
    
    p = f(&p); 
    n = *p;
    
    free(p);

    printf("n = %d", n);
    
    return 0;
}

int* f(int** p) {
    *p = (int*)malloc(sizeof(int));
    **p = 320;
    
    return *p; 
}



/*
run:

n = 320

*/

 



answered Jul 7, 2024 by avibootz

Related questions

1 answer 211 views
2 answers 273 views
1 answer 119 views
119 views asked Nov 30, 2023 by avibootz
1 answer 100 views
100 views asked Jan 31, 2023 by avibootz
1 answer 188 views
1 answer 147 views
147 views asked May 4, 2021 by avibootz
...