08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Arrays

You can change 40 to any size you wish. If in has been declared as FILE *, we can prompt the

user for the file name and test if everything is okay with this:

printf("Enter name of file: ");

scanf("%s", dataFile);

if ((in = fopen(dataFile, "r")) == NULL) {

printf("File cannot be found\n");

exit(1);

}

Since we are using %s to read the name of the file, the name may not contain a space. If your

file name may contain a space, you can use gets.

8.7 Array as Argument to a Function

In Chapter 7, we saw how arguments are passed to functions. In C, arguments are passed

“by value.” When an argument is passed “by value,” a temporary location is created with the value

of the argument, and this temporary location is passed to the function. The function never has

access to the original argument.

We also saw that when, for instance, we use gets(item) to read a string into the character

array item, the function is able to put the string into the argument item. This implies that the

function has access to the actual argument – no copy is involved.

In C, an array name denotes the address of its first element. When we use an array name as an

argument to a function, the address of the first element is passed to the function that, therefore,

has access to the array.

We now take a closer look at some issues involved in writing functions with array arguments.

We will write a function, sumList, which returns the sum of the integers in an array passed to

the function. For example, if the array contains the following:

the function should return 24.

We could write the function header like this:

int sumList(int num[])

The array argument is written just like an array declaration but with no size specified.

However, the square brackets must be present to distinguish it from a simple argument. For

instance, if we had written int num, this would mean that num is an ordinary int variable.

You can specify a size, if you wish, using a constant, a symbolic constant, or any integer

expression that can be evaluated at the time the program is compiled. (C99 and later versions of

C allow variable-length arrays in which an array subscript can be specified at runtime. We will see

an example in Section 9.4.1.) However, your program will be more flexible if you do not.

211

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!