C Arrays

Basic Usage

Multiple dimension arrays

Example

  #include <stdio.h>
  int main (void) {
    char a[2][4] = { {'w','o','w','\0'}, {'h','i','\0','X'} };
    int i, j;
    for (i = 0; i < 2; i++)
        for (j = 0; j < 4; j++)
            printf("a[%d][%d] is %c\n", i, j, a[i][j]);
    for (i = 0; i < 2; i++)
            printf("row a[%d] is %s\n", i, a[i]);  // a[i] is a char array (i.e. a string)
    return 0;
  }

Arrays and Functions

Use [] to indicate an array variable in function definition and in function prototype, e.g.

      void doArray (int [], int); /* prototype version */
      void doArray (int myarray[], int size) /* on function itself */

If declaring a multi-dimensional array as function argument, need sizes of subcripts for all dimensions but 1st <ul> <li>eg: void passarray(int a[][3][4]) receives a 3 dimensional array </li> <li>Sizes needed because arrays are stored sequentially - need dimensions to locate items </li> <li>Another example of low-level nature of C data structures. </li></ul>

Can use const in parameter list to make array unmodifiable: void doArray (const int ma[]) results in compile error if any attempt to assign or read new value into an array element

Command line options

To read what arguments if any were on a command line invocation, use the following main function declaration:
main(int argc, char *argv[])

Example: given ./a.out one two
argc is 3, argv[0] is “./a.out”, argv[1] is “one”, and argv[2] is “two”

CAUTION: review the below sections after learning pointers

Pointers and arrays

Welcome to C’s Wacky World

int *ptr and int a[10] variables are often interchangeable but not 100%:

Arrays of pointers

See also the Pointers & Dynamic Memory Allocation notes resource.