How to return a pointer to an array of int pointers from a function in C

1 Answer

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

// Function to allocate and initialize a 2D array
int **getPointers(void) {
    int **array;  // Pointer to an array of int pointers
    int i;

    // Allocate memory for two int* pointers (representing two rows)
    array = calloc(2, sizeof(int *));

    // Allocate memory for three integers in each row
    array[0] = calloc(3, sizeof(int));  // First row
    array[1] = calloc(3, sizeof(int));  // Second row

    // Initialize the arrays with example values
    for(i = 0; i < 3; i++) {
        array[0][i] = 100 + i;  // First row: 100, 101, 102
        array[1][i] = 200 + i;  // Second row: 200, 201, 202
    }

    // Return the pointer to the 2D array
    return array;
}

int main() {
    int **pp;  // Pointer to hold the returned 2D array
    int i;

    // Call the function to get the initialized 2D array
    pp = getPointers();

    // Print the contents of both arrays
    for(i = 0; i < 3; i++) {
        printf("a[%d] = %d\n", i, pp[0][i]);  // Print first row
        printf("b[%d] = %d\n", i, pp[1][i]);  // Print second row
    }

    // Free the dynamically allocated memory
    free(pp[0]);  // Free first row
    free(pp[1]);  // Free second row
    free(pp);     // Free the array of pointers

    return 0;
}


/*
run:

a[0] = 100
b[0] = 200
a[1] = 101
b[1] = 201
a[2] = 102
b[2] = 202

*/

 



answered Nov 10, 2025 by avibootz

Related questions

...