How to  return two pointers from a function in C

1 Answer

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

// Define a struct to hold two pointers
typedef struct {
    int *ptr1;
    int *ptr2;
} TwoPointers;

// Function that returns a struct containing two pointers
TwoPointers getPointers() {
    TwoPointers result;
    result.ptr1 = malloc(sizeof(int));
    result.ptr2 = malloc(sizeof(int));

    if (!result.ptr1 || !result.ptr2) {
        fprintf(stderr, "Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }

    *result.ptr1 = 100;
    *result.ptr2 = 200;

    return result; // Struct is returned by value
}

int main() {
    TwoPointers tp = getPointers();
    printf("Values: %d, %d\n", *tp.ptr1, *tp.ptr2);

    // Free allocated memory
    free(tp.ptr1);
    free(tp.ptr2);
    
    return 0;
}


/*
run:

Values: 100, 200

*/

 



answered Nov 10, 2025 by avibootz
...