ProgrammingC Developer

How does the argument passing mechanism work in C language? How to avoid type errors when passing variables of different types, structures, and arrays?

Pass interviews with Hintsage AI assistant

Answer.

In C language, arguments to functions are always passed by value. This means that the function receives a copy of the argument's value. This is evident for simple types (int, float): changes inside the function do not affect the original variable. However, there are nuances with arrays and structures:

  • When an array is passed to a function, a pointer to its first element is actually passed, not the entire array. However, the pointer itself is still passed by value.
  • For structures, you can explicitly pass a copy (by value), but it is more efficient to do so via a pointer — this way the function can modify the original structure.

Example: handling an array and a structure

#include <stdio.h> typedef struct { int a; int b; } Pair; void modifyArray(int arr[], int size) { arr[0] = 42; // modifies the original array } void modifyStruct(Pair s) { s.a = 100; // only changes the local copy } void modifyStructPtr(Pair *s) { s->a = 200; // changes the original via pointer } int main() { int nums[2] = {1, 2}; Pair p = {10, 20}; modifyArray(nums, 2); modifyStruct(p); modifyStructPtr(&p); printf("nums[0]=%d, p.a=%d\n", nums[0], p.a); // nums[0]=42, p.a=200 return 0; }

Tricky Question.

Question: If a function is declared as void func(int arr[10]), will this array inside the function always have 10 elements?

Answer: No. The notation int arr[10] in the parameters is actually equivalent to int *arr — the size of the array is lost when passed. The function does not know the actual length of the array, so always take an additional parameter with its length. Otherwise, you may encounter array out-of-bounds and UB.

Example:

void foo(int arr[10]) { printf("%d\n", arr[9]); // arr does not necessarily contain 10 elements! }

History

In a signal processing project, an array was passed through a function assuming its length was always the same, but in one case, a smaller array was passed. The result was accessing out of memory bounds, crashing the application, and causing unpredictable behavior on the controller.


History

In banking software, an attempt was made to modify a structure by passing it by value instead of by pointer. Changes were not saved, causing the processing module not to update the state of accounts, leading to calculation errors.


History

In a telemetry system, a student added a function to clear an array but forgot to pass the length, and the arrays were of different sizes. The error was discovered only after collecting a large volume of incorrect data and a long time spent searching for bugs.