Skip to content
hengxin edited this page Nov 9, 2017 · 3 revisions

Tutorials on Arrays

Declaration

  • int foo[5];

These are arrays whose number of dimensions and their size are known at compile time. Array bucket values are stored in contiguous memory locations (thus pointer arithmetic can be used to iterate over the bucket values), and 2D arrays are allocated in row-major order.

Statically declared arrays can be declared as either global or local variables.

  • int *p_array = (int *)malloc(sizeof(int)*50);

Dynamically allocated arrays are allocated on the heap at run time. The heap space can be assigned to global or local pointer variables that store the address of the allocated heap space (point to the first bucket).

To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.

  • malloced array VS. variable-length-array

    • You can free() a malloced array, but you can't free() an VLA (although it goes out of scope and ceases to exist once the enclosing block is left). In technical jargon, they have different storage duration: allocated for malloc versus automatic for VLAs.
    • Although C has no concept of a stack, many implementation allocate an VLA from the stack, while malloc allocates from the heap.
    • malloced memory can be changed in size with realloc(), while VLAs can't.

Multi-dimentional Arrays

Since C99, C has 2D arrays with dynamical bounds.

int array[m][n];  // then initialize it

If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following:

int (*array)[n] = malloc( sizeof(int[m][n]) );	// allocated on the heap
array[i][j]  // for access
free(array)  // don't forget
int **array = (int**) malloc (nrows *sizeof(int*));

for (int i = 0; i < nrows; ++i)
    array[i] = (int*) malloc( ncols * sizeof(int) );

Initialization

  • int foo[5] = {1, 2, 3, 4, 5};
  • int foo[5] = {0};
  • int foo[] = {1, 2, 3, 4, 5};

Input

for (int i = 0; i < LEN; i++)
    cin >> keywords[i];

Output

Cases

Clone this wiki locally