Return an Array in C
×

Return an Array in C

70

 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* returnA() {
static int B[5] = {2, 3, 4 ,5, 6};
return B;
}
int main() {
int* returnedA= returnA();

printf("Returned Array: ");

for (int i = 0; i < 5; i++) {
printf("%d ", returnedA[i]);
}
printf("\n");

return 0;
}
Output:

Returned Array: 2 3 4 5 6


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