C - Functions Returning Pointers

In C, functions can return pointers just like they can return other data types. Returning pointers from a function allows you to dynamically allocate memory and return the address of that memory location, providing a way to pass data back to the caller.

Example:


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

// Function that dynamically allocates an array of integers and returns a pointer to it
int* createArray(int size) {
    int *arr = (int*)malloc(size * sizeof(int)); // Allocate memory
    if (arr == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        exit(1);
    }

    // Initialize the array elements (for demonstration)
    for (int i = 0; i < size; i++) {
        arr[i] = i * 2;
    }

    return arr; // Return the pointer to the dynamically allocated array
}

int main() {
    int size = 5;
    
    // Call the function to create an array
    int *myArray = createArray(size);

    // Use the returned array
    for (int i = 0; i < size; i++) {
        printf("Element %d: %d\n", i, myArray[i]);
    }

    // Free the allocated memory when done
    free(myArray);

    return 0;
}
    

In this example:

  • The createArray function dynamically allocates an array of integers using malloc. It returns a pointer to the allocated memory.
  • The main function calls createArray to obtain a dynamically allocated array and then uses it.
  • After using the dynamically allocated memory, it's essential to free it using free to avoid memory leaks.

Output:


Element 0: 0
Element 1: 2
Element 2: 4
Element 3: 6
Element 4: 8
    

Keep in mind that when a function returns a pointer, the caller is responsible for managing the allocated memory and freeing it when it is no longer needed to prevent memory leaks.