Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Teach Your Child To Read

Disclosure: My content contains affiliate links.

31,647 questions

41,700 answers

573 users

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

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Jul 7 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

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Jul 7 by avibootz

Related questions

1 answer 80 views
2 answers 150 views
1 answer 47 views
1 answer 32 views
32 views asked Nov 30, 2023 by avibootz
1 answer 30 views
30 views asked Jan 31, 2023 by avibootz
...