CS 202 - Notes 2016-02-17

Intro to C

Much of C’s syntax will feel very familiar coming from Java

Things that are similar: semicolons, {} blocks, function syntax, typed integer declarations, for loops, while loops, if statements

Deconstructing main

every program must have a main – it is the starting place of your program

int main(inst argc, char * argv[])

The return value is returned to the calling process, and it tells the process if the program completed successfully or not. We typically return 0 to indicate no errors occurred and -1 if there was an error.

The arguments of main give us access to the command line arguments with which the program was called.

Pointers

C gives us access to memory at a low level through pointers, which can hold memory addresses

declare a pointer: int * p;. This creates a new variable p, which can hold the address of an integer in memory. The type of p is “integer pointer”.

To access memory at the location stored in a pointer, we use * to dereference it. In other words, *p can be treated like an integer variable and used as a value in expressions, or it can be assigned to on the left side of assignment statements.

Important, a declaration of a pointer only creates a location in memory that can hold an address, it does not also create a location for the integer value it refers to. Do not dereference a pointer without first assigning it to a valid location of the appropriate value.

To get the address of an existing variable, we use &.

Example: Create an integer variable x and a integer pointer xp, and then set xp to hold the address of x.

int x = 5;
int * xp = &x;