How to initialize a pointer in a separate function with C

1 Answer

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

void initializePointer(int **pp, int size) {
    *pp = (int *)malloc(sizeof(int) * size); 
    if (*pp != NULL) {
        **pp = 98; 
    }
}

int main() {
    int *p = NULL; 

    initializePointer(&p, 5); // Pass the address of the pointer to the function

    if (p != NULL) {
        p[1] = 100;
        printf("%d %d\n", *p, p[0]);
        printf("%d %d\n", *(p + 1), p[1]);
        free(p); 
    } else {
        printf("Memory allocation failed.\n");
    }

    return 0;
}
 
   
   
/*
run:
   
98 98
100 100
   
*/

 



answered Dec 28, 2024 by avibootz

Related questions

2 answers 240 views
1 answer 131 views
1 answer 159 views
2 answers 157 views
1 answer 165 views
165 views asked May 16, 2022 by avibootz
...