Skip to study material
← Question index

QUESTION 14 · Arrays and Functions

Explain passing individual array elements as function arguments.

5 marks

Answer in brief

An individual array element can be passed to a function in the same way as another value of its element type.

Value argument

In show(a[1]), a[1] selects one element and its value is passed to the parameter. For an int parameter, that parameter is a separate object. Assigning to it does not assign to the original array element. This follows C’s pass-by-value rule.

Example trace

The sample starts with a[1] equal to 20. change(a[1]) gives the function’s parameter n the value 20. The function assigns n = 99 and prints it. When it returns, a[1] still contains 20. The two printed values demonstrate that only a value was supplied.

Address argument

A call such as change_at(&a[1]) could pass the address to an int * parameter. Assigning through that valid pointer could change the selected element. The pointer value is still passed by value; the object reached through it is shared. Detailed pointer operations belong to Unit V.

Important rules

  1. Use a valid subscript before making the call.
  2. Keep the parameter type suitable for the selected element.
  3. Do not confuse passing one element, such as a[i], with passing the array expression a.
  4. A function prototype helps the compiler check the intended argument types.

Complexity

Selecting and passing one fixed-width element takes constant work in the usual model. The function’s own processing determines any additional complexity. The example uses O(1) time and O(1) extra space.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void change(int n)
{
    n = 99;
    printf("Parameter = %d\n", n);
}

int main(void)
{
    int a[3] = {10, 20, 30};
    change(a[1]);
    printf("Element = %d\n", a[1]);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Parameter = 99
Element = 20

Related exam questions

Related questions in the array function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • July 2021 · Q7 · 15 marks

    Illustrate passing arrays to functions with a relevant example program.

    Paper P04 · page 1
  • January/February 2024 · Q9(b) · 5 marks

    Explain passing an entire array as an argument to a function, with an example.

    Paper P10 · page 2

View this category in the exam question bank →