Arrays and Pointers in C

Array Declarations

int a[5];
char s[30];
double a[5][7];

Array References

for (int i = 0; i < n; i++) {
  a[i] = i;
}

Array Sizes

Prior to C99, sizes had to be constants. Now sizes can be variables.

reverse.c

Array Initializers

int a[3] = { 1, 2, 3 };
int a[2][5] = {
  {1, 2, 3, 4, 5},
  {6, 7, 8, 9, 10}
}
char s[3] = { 'a', 'b', 'c' };
char s[4] = "abc";
char *a[3] = { "foobar", "xyzzy", "plugh" };

Linear Search

/*
  lsearch - searches an array of strings for target.

  returns the position of the first occurrence of target or -1
  if target does not occur.
*/

int lsearch(int n, char *a[n], char *target) {
  int i = 0;

  while (i < n && strcmp(target, a[i]) != 0) {
    i++;
  }
  if (i < n) return i;
  else return -1;
}

Pointers

A pointer variable stores the address of a data item.

Pointer Declarations

int *p;
char *s = "foobar";
double *x = &y;

Address and Dereference Operators

Pointer Example

int x = 3;
int *y = &x;
(*y)++;

This increments x!

Pointers vs Arrays

Dynamic Allocation

Dynamic Arrays vs Variable Length Arrays

Strings

String Functions

  • Read man string for others.
  • Manipulating Strings

    Reading Strings