← Back to Home

CITS2002 - Lecture 4
Arrays - Slides

Introduction to Memory

  • Computer memory is addressable
    • Each memory location has a unique address
  • Modern computers are 64 bit
    • Every location has a 64 bit address
  • There are possible addresses for a 64 bit computer
    • However, the RAM does not have all those addresses
      • The computer would otherwise be too expensive
    • Don’t need all that memory because of virtual memory system
  • Compilers optimise memory allocation to save space

64 bits of memory is divided into 8 bytes

What is a Word?

A word is a fixed-size unit of data that a processor can read from or write to memory in one operation

  • Its size depend on the architecture of the CPU:
    • 16-bit CPU → 1 word = 16 bits = 2 bytes
    • 32-bit CPU → 1 word = 32 bits = 4 bytes
    • 64-bit CPU → 1 word = 64 bits = 8 bytes

Terminating Strings

  • The null byte \0 has special significance
  • Whenever we use arrays to represent strings, we mark the end of them with the null byte
    • This tells the compiler where the string ends
  • strlen() ignores the null byte when outputting string length
    • Many functions depend on the null byte to stop reading the string
int main() {
    char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // properly terminated
    char wrong[5] = {'H', 'e', 'l', 'l', 'o'};      // missing '\0'
 
    printf("With null terminator: %s\n", word);
    printf("Without null terminator: %s\n", wrong); // may print garbage after "Hello"
}

Copying Strings

  • Copying strings is a bit harder because we represent them using arrays

Example string copy function:

// DETERMINE THE STRING LENGTH, THEN USE A BOUNDED LOOP
 
void my_strcpy(char destination[], char source[]) { 
	int length = strlen(source);
	
	for(int i = 0 ; i < length ; ++i) {
		destination[i] = source[i];
	}
	
	destination[length] = '\0';
}

Formatting Results into Character Arrays

  • sprintf() writes formatted output to a string instead of the screen
    • Essentially, we store our string in a variable using this function!
  • sprintf(char *str, *format, ...)
    • str: pointer to an array of characters where string is stored
      • Size needs to be defined beforehand
      • When it is passed through sprintf() it becomes a pointer
        However, its defined as an array
    • format: pointer to a null-terminated string that contains the text to be written to the string str
      • May include format specifiers that control how later arguments are formatted into the string
int main() { 
	char buffer[100]; 
	float pi = 3.14159; 
	sprintf(buffer, "The value of pi is %.2f.", pi); 
	printf("%s\n", buffer); 
	return 0; 
}
  • snprintf() is a safer variation that lets us specify the max # of characters to copy
    • This prevents us from exceeding the maximum length of the array
  • snprintf(char *str, size, *format, ...);
    • Works same as above just with additional size property
int main() {
    char buffer[10];
    snprintf(buffer, sizeof(buffer), "HelloWorld");
    printf("%s\n", buffer); // prints: HelloWorl
    return 0;
}
  • In the code above, the array must reserve memory for the null-terminator, meaning it only has 9 spaces for our string
    This cuts off the ‘d’ in “HelloWorld”

  • Arrays in C can only contain one type of data
    e.g. int, float, etc.
  • This is not ideal when we need to link different data types together
    • e.g. linking a team’s name to their season wins
  • We want to collect related data together into a single structure

Defining Structures

  • Structures (also called structs) are a way to group several related variables into one place
  • Each variable in the structure is known as a member of the structure
  • Unlike an array, a structure can contain many different data types
struct MyStructure {   // Structure declaration  
  int myNum;           // Member (int variable)  
  char myLetter;       // Member (char variable)  
}; // End the structure with a semicolon

Array of Structures

We can also have arrays where each element is a structure! This helps us avoid using multiple parallel arrays by grouping them together

#define MAX_TEAMS 3
#define NAME_LEN  20
 
// defines structure named Team
struct Team {
    char name[NAME_LEN];
    int played, won, lost, points;
};
 
// defined an array of structures called league
// each element is a Team struct
struct Team league[MAX_TEAMS] = {
    {"Eagles", 22, 15, 7, 60},
    {"Dockers", 22, 12, 10, 50},
    {"Hawks", 22, 10, 12, 45}
};

CITS2002 - Lecture 6