Return an Array in C
×


Return an Array in C

422

 Returning an array in C is like giving back a collection of data from a function.

 It's similar to handing over a gift to the main part of your code.

 code easier because different tasks are divided into functions.

When a function returns an array, it's like saying, Here's the data you asked for.

 When a function hands back an array in C, it's like giving you a bunch of data to work with.

 You can then use that data however you like.

 This makes your code tidy and easier to understand and change later.

Return an array in C Explanation 

 returnArray: This is a function in C responsible for creating and initializing an array. It then returns this array.

 Inside returnArray: We have a static array that is initialized with values. This array is the one we want to return to the main function.

 The function returns the array.

 main: This is the main function of our program.

 Inside main: We declare a pointer to hold the returned array. We call the return array function and assign its returned array to our pointer.

 We can then use this pointer to access and manipulate the elements of the returned array as needed.

Example:

#include<stdio.h>

int* createArrayStatic() {
    static int arr[5] = {1, 2, 3, 4, 5};
    return arr;
}

void printArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int *result = createArrayStatic();
    printf("Returned Array from static function: ");
    printArray(result, 5);
    return 0;
}
Output:

Returned Array from static function: 1 2 3 4 5 


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments