• Home
  • 6.13 Returning Array-Related Data

6.13 Returning Array-Related Data

View Categories

6.13 Returning Array-Related Data

C does not allow a function to return an array directly. A function can instead return a pointer to an array element, provided the pointed-to storage remains valid after the function returns.

#include <stdio.h>

int *getElement(int numbers[], int index)
{
    return &numbers[index];
}

int main(void)
{
    int values[] = {10, 20, 30, 40, 50};

    int *ptr = getElement(values, 2);

    printf("Returned value: %d\n", *ptr);

    *ptr = 99;

    printf("Updated array element: %d\n", values[2]);

    return 0;
}

Example Output #

Returned value: 30
Updated array element: 99

Explanation #

The function declaration:

int *getElement(int numbers[], int index)

specifies a return type of int *. The function returns a pointer to an element of the supplied array.

return &numbers[index];

returns the address of the selected element. Because the array belongs to main() and remains alive while the pointer is used, the returned pointer is valid in this example.

The pointer can read or modify the selected element:

*ptr = 99;

This changes values[2] to 99.

Returning Array-Related Data #

Method Description
Return a pointer to an element Returns an address within an existing array
Return a pointer to dynamically allocated memory Returns allocated storage that the caller must eventually release
Return a structure containing an array Returns the structure by value, including its array member
Fill a caller-provided array Writes results into storage supplied by the caller

Important: A function must not return a pointer to an ordinary local array whose lifetime ends when the function returns. Such a pointer becomes invalid, and dereferencing it causes undefined behavior.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *