C One-Liners

1999, Dr. David Matuszek

This is a collection of C "one-liners": useful things to remember about C that are very brief (if not always a single line). I made up this list when I was first learning C; you might also find it helpful.

Suggested additions and improvements are always welcome.

Function parameters

To declare an integer: int n;

To assign a value to an integer: n = 5;

To declare and assign a value to an integer: int n = 5;

To pass a constant integer to a function: foo(n)

To receive a constant integer as an argument:  void foo (int n) {

To pass a pointer to an integer (so the integer can be changed):  foo (&n)

To receive a pointer to an integer:  void foo (int *n) {

To assign a value to an integer through a pointer: *n = 5;

A function gets a pointer to an array, but it gets a copy of a struct.

Strings (being arrays) are always passed as pointers.

Arrays, strings, and pointers

"Declaring" a variable tells its type; "defining" it also allocates space.

a[i] always means exactly the same as *(a + i). Hence, a[5]==5[a].

If a[100] is an array, a (by itself) is a pointer to the zeroth element.

A char* is a variable pointer, while a char[] is a constant pointer.

The declaration char *c  means that c is a char* and *c is a char.

To define a string in a fixed location: char fixed[100];

To define a pointer to a string: char *strptr;

A string extends from whereever a pointer points, up to the first zero byte.

To allocate space for a string and set a pointer to it:  strptr = (char *) malloc (100);

When you malloc space for a string, remember to add 1 for the zero byte.

To assign a value to a string: strcpy (str, "hello");

To define a "string" type:  typedef char *string;

To step through a string:   for (p = str; *p !=0; p++) printf ("%c", *p);


To declare a struct:
   typedef struct thing {
      int foo;
      int bar;

Structs and typedefs are normally declared at the top level (not inside a function).

To define a struct variable:  struct thing s;

To be able to say thing s; instead of struct thing s; define typedef struct thing thing;

If you declare a struct on a single line, be extra careful to get the ;}; right.

To define an array of struct:  struct thing a[100];

To refer to the fields of a struct:  s.foo = s.bar;

To call a function with a pointer to a struct:  foo (&s);

To define a function with a pointer-to-struct parameter:  void foo (thing *p);

To refer to the fields of a struct through a pointer, use either (*p).foo or p -> foo.