简体   繁体   中英

How do I make my array available to other functions?

I have an array declared in my main() function, and I need to access it in a function that is being called from main(). How do I make the array available to the function? And what is the best way to do this? I tried to use the static keyword, but that did not change anything. Should I declare the array outside of main() as well as the function being called?

How do I make the array available to the function?

In C, you can pass variables like arrays to functions by putting the name of the variable in the parentheses of the function you're calling.

And what is the best way to do this?

Let's say you had the following code:

void INeedNums(int nums) {
    // Do something with them nums.
}
int main() {
    int aBunchofNums[] = {1,2,3,4};
    INeedNums(aBunchofNums);
}

This code would send the entire array of {1,2,3,4} to the function for it to work with.

Should I declare the array outside of main() as well as the function being called?

You can declare it outside of the main() function, making it an external variable . External variables can be accessed by any function.

The code above sends the array to a function, where the function can use it. Notice how that function establishes a new variable called int nums in order to handle it, that means it's not using the same exact variable, which means that when you edit the array within that second function, it does not change the array that resides in main() that you sent to it. There are several methods to changing this, namely using pointers, like in P__J__'s answer.

You can pass it as the argument to the other function, or may declare it global.

Examples - and exercise to understand the scopes of the variables:

int array[100]

int add(size_t first, size_t second, size_t result )
{
    array[result] = array[first] + array[second];
    return array[result];
}

int add1(int *array, size_t first, size_t second, size_t result )
{
    array[result] = array[first] + array[second];
    return array[result];
}


void foo1(void)
{
    int array[100];

    add1(array, 5, 7, 9);
    add(5, 7, 9);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM