ProgrammingC Developer

What is the difference between pointers and arrays in C? How to properly pass an array to a function?

Pass interviews with Hintsage AI assistant

Answer.

Pointers and arrays in C are related, but they are not the same:

  • Array — a collection of homogeneous elements in memory, defined by size.
  • Pointer — a variable that holds the address in memory that an array or a single object can point to.

When passing an array to a function, a pointer to the first element of the array is actually passed (therefore, sizeof inside the function does not give the size of the entire array, but only the size of the pointer).

Syntax for passing:

void foo(int arr[], int size) { // arr — actually int* for (int i = 0; i < size; ++i) printf("%d\n", arr[i]); } int main() { int data[5] = {1,2,3,4,5}; foo(data, 5); }

Trick question.

Question: What will the expression sizeof(arr) return inside the function if arr is a parameter of type int arr[]?

Answer: Returns the size of the pointer (sizeof(int*)), not the size of the entire array. Because a pointer to the first element is passed to the function, information about the length is lost.

Example code:

void printSize(int arr[]) { printf("%zu\n", sizeof(arr)); // sizeof(int*) is usually 4 or 8 }

History

In a commercial project, a piece of code was written to calculate the average value in an array, where the number of elements inside the function was calculated using sizeof(arr) / sizeof(arr[0]), which always returned 1 or 2 instead of the actual number of elements. As a result, the program malfunctioned with the data and incorrectly averaged the values.


History

In one project, a dynamically allocated array was passed to a function without separately storing its length (size). As a result, the function did not know how many elements were allocated, leading to out-of-bounds access, leaks, or memory corruption.


History

By mistake, a fixed-size array was used as a pointer, and some compilers allowed directly assigning through memcpy the entire array instead of its elements. This led to an obscure error where parts of the data structure were lost or stack overflow occurred.