Skip to content

CS50 Week 2: Arrays

On arrays, strings (or are they?) and functions.

Written by Eva Dee on (about a 3 minute read).

What is compiling? permalink

Compiling actually involves four steps:

  1. preprocessing - evaluating libraries and imports
  2. compiling - translating your code into assembly code
  3. assembling - translating assembly code into binary
  4. linking - linking all the different files into one

Debugging permalink

  • Syntactic errors vs logical errors
  • using the debugger and breakpoints

Memory permalink

  • think of RAM (random-access memory) as a grid, 1 byte taking one space inside the grid.
// this is inside CS50 IDE
bool 1 byte
char 1 byte
double 8 bytes
float 4 bytes
int 4 bytes
long 8 bytes
string ? bytes

Arrays permalink

  • Arrays are used to hold values of the same data type.
  • Arrays can be multidimensional.
  • Array values are passed by reference.

With arrary declaration, you need to specify three things:

  • type

  • name

  • size

What is a (damn, you) segmentation fault ?

When you work with data outside of your declared array. Example, you have an array with size 10, but you are accessing the element at position 11.

🤔 What is the difference between conversion, casting, coercion?

  • Conversion: either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer.
  • Coercion: an implicit conversion.
  • Casting: an explicit type conversion int() or Number()

String permalink

How do we know when the string ends?

  • \0 null (terminating) character where you basically "waste" one byte to indicate where the string ends.
  • So a string with length 3, actually takes up 4 bytes.
  • In conclusion: strings are actually just arrays of characters (there is no 🥄!)

Food for thought 🤔

  • The whole point of programming ultimately is to abstract those lower-level implementation details.

Command-line arguments permalink

  • argv - argument vector aka an array of arguments
  • By default, main returns 0.
  • 0 in computer speak typically means all ok 👍
int main(int argc, string argv[])
{
printf("hello, %s\n", argv[1]);
}
else
{
printf("hello, world\n");
}
  • argc: argument count. The program's name is by default, the first argument
  • argv: argument vector (vector is another word for array), is an array of strings. The first element argv[0] is always the name of the program. The last element is always stored at argv[argv-1]

Functions permalink

  • synonyms: procedures, methods, subroutines

There are three parts in a function declaration:

  1. return type
  2. name
  3. the argument list (comma-separated, with a type and a name)

🤔 What is the difference between function declaration vs function definition?

float sum_two (int a, int b);

// the definition (aka the actual recipe)
float sum_two (int a, int b)
{
  int result =  a + b;
  return result;
}
  • Functions can have 0 (void) arguments or no output (also void).