Main Content

Passing arrays into functions in C

Archive - Originally posted on "The Horse's Mouth" - 2014-12-02 15:19:09 - Graham Ellis

When passing arrays into functions in C, you can specify just the array name and C will pass in a pointer to the first element of the array (i.e. &abc[0] is the same as saying just abc ). Within your functions, you can then use array style notation with square brackets, or pointers.

There's an example from the C course I'm running at the moment - [here] ... main code is

  main(){
  
    int stock[10];
    int k;
  
    for (k=0; k<10; k++) stock[k] = 100;
  
    int bobBuys[10];
    for (k=0; k<10; k++) bobBuys[k] = 0;
    bobBuys[4] = 50;
    bobBuys[6] = 10;
  
    updateStock(stock,bobBuys);
  
    showStock(stock);
  
}


You'll note how an apparently basic facility turns out to be rather elegant in how it calls up functions to ooerate on arrays as a whole, aided by the fact that passing an array is the same as passing the address of the first element.

Jelly Bean Picture? The example is all about stock levels and sales of Jelly beans