Home >Backend Development >C++ >How Can I Return and Access an Array from a C Function?

How Can I Return and Access an Array from a C Function?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 00:29:24303browse

How Can I Return and Access an Array from a C   Function?

Returning an Array in a Function

In C , it's often necessary to return arrays from functions. The question below explores this topic:

Question:

Consider an array int arr[5] passed to the function fillarr(int arr[]).:

int fillarr(int arr[])
{
    for(...);
    return arr;
}

a) How can we return the array?
b) If we return a pointer, how do we access it?

Answer:

a) The array variable arr can be treated as a pointer to the beginning of its memory block. The following syntax:

int fillarr(int arr[])

is equivalent to:

int fillarr(int* arr)

Therefore, we can return a pointer to the first array element:

int* fillarr(int arr[])

b) To access the returned pointer, we can use it like a normal array in the calling function:

int y[10];
int *a = fillarr(y);
cout << a[0] << endl;

The above is the detailed content of How Can I Return and Access an Array from a C Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn