I have question regarding array size declaration in C. I see that if I declare an array in the main function without specifying its size like

int arr[]; arr[0] = 7; arr[1]= 8;

it shows an error whereas if I declare an array as a parameter of a function without declaring its size it doesnt show any error as below

void function(int arr[])
   arr[0] = 2;

I wanna know if it is important to declare array size at the time of its declaration be it 1D,2D OR multidimensional array in C.

  • As you know local variables are stored in stack for example when you declare int x then the compiler preserve a space in memory for this datatype so when you declare unknown space variable like int arr[] then compiler is unable to allocate memory Here void function(int arr[]) i think you are passing a predefined array which the compiler knows it's space – Mahmoud Ali shaltoot Sep 20 '18 at 16:27

In C, when you declare an array, it's size MUST be declared when it is created. There is no mechanism built into C for dynamic array RE-sizing. An array's size is declared explicitly by a statement like int array[12]; or implicitly by initializing it at creation. For example, int array[] = { 31, 25, 16, 5, 2, 2, 8, 21 }; would create an int array with 8 elements and would initialize it with the given values.

Your example with the function is a different situation. The function isn't creating an array, it's using an existing one.

When an array is a parameter given to a function, it isn't creating a new array, it's actually passing an address of an existing array. So, while the address of the array is passed by copy (the address of the array is copied to the function as a parameter, while the original array variable that contains the array address will not be touched by the function), the function will actually be working with the original array contents.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Ahhh....That's such a beautiful explanation, thank you! I wonder how come you guys know such wonderful answers to lower level implementation details. – sk.76 Sep 22 '18 at 8:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .