Chapter 5 and 6: Pointers and Parameter Passing, 2D-Arrays and Library Functions

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/12

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

13 Terms

1
New cards
  • a pointer is a variable that stores a memory address (the location of another variable in memory)

  • declaration: <type> *<variable_name>;

    • int *p; // p is a pointer to an integer

  • visualisation: think of a pointer as a box that doesn’t store a value directly, but instead stores an arrow pointing to another box (variable)

what is a pointer

2
New cards
  • address-of operator (&): returns the memory address of a variable

    • int a = 10;

    • p = &a; // p now points to a, i.e., it stores the address of a

  • dereference operator (*): accesses the value std at the memory held by the pointer

    • int value = *p; // value is now 10 (the value of a)

    • *p = 20; // this changes the value of a to 20

key pointer operators

3
New cards
  • critical: always intialise a pointer before using it

  • an unitialised pointer is a ‘bad pointer' (or ‘wild pointer’) and points to a random memory location

  • dereferencing a bad pointer is a severe error that can crash your program or cause unpredictable behaviour
    int *p; // p is uninitialised (bad pointer)

    *p = 5; // ERROR: Writes 5 to a random memory location!

pointer initialisation and the “bad pointer”

4
New cards
  • a special value that means ‘this pointer points to nothing’

  • initialisation: int *p = NULL;

  • use case: used to indicate that a pointer is not currently valid

  • safety: always check if a pointer is NULL before dereferencing it to avoid crashes
    if (p != NULL) {

    *p = 10; // Safe to use

    }

    // Or, more concisely:

    if (p) {

    *p = 10;

    }

  • dereferencing a NULL pointer will cause a program crash (a segmentation fault)

null pointers

5
New cards
  • pointers can point to structures, just like any other type

    • typedef struct { int x; int y; } Point;

      Point location;

      Point *ptr = &location;

  • accessing struct members via a pointer:

    • method 1 (explicit dereference): (*ptr).x = 10l // Parentheses are necessary because . has higher precedence than *

    • method 2 (arrow operator ->): ptr->x = 10; // This is the preferred and more common syntax

pointers to structures

6
New cards
  • this solves the ‘call by value’ limitation from chapter 4

  • by passing a pointer to a variable, a function can modify the original variable

  • example: the correct swap function
    // Correct version using pointers

    void Swap(int x, int y) {

    int temp = *x; // temp gets the value at address x

    x = y; // value at address x becomes value at address y

    *y = temp; // value at address y becomes temp

    }

    int main(void) {

    int a = 10, b = 20;

    Swap(&a, &b); // Pass the ADDRESSES of a and b

    printf("a=%d, b=%d", a, b); // Output: a=20, b=10

    }

pointers as function parameters (call by reference)

7
New cards
  • this is a fundamental concept in C

  • an array name is, in most contexts, treated as a pointer to the first element of the array

    • int numbers [10];

    • numbers is equivalent to &numbers[0] (the address of the first element)

  • why arrays are ‘call by reference’: when you pass an array to a function, you are actually passing a pointer to its first element, this is why functions can modify the original array
    // These two function prototypes are EQUIVALENT

    int SumArray(int nums[], int numElements);

    int SumArray(int *nums, int numElements);

  • inside the function, nums[i] is just syntactic sugar for *(nums + i)

what is the connection between pointers and arrays

8
New cards
  • an array of arrays, think of it as a grid with rows and columns

  • declaration: <type> <name>[<num_rows>][<num_columns>];

    • int matrix[4][3]; // a 4-row, 3-column array of integers

  • visualisation:
    matrix[0][0] matrix[0][1] matrix[0][2]

    matrix[1][0] matrix[1][1] matrix[1][2]

    matrix[2][0] matrix[2][1] matrix[2][2]

    matrix[3][0] matrix[3][1] matrix[3][2]

  • initialisation:
    int matrix[2][3] = {

    {1, 2, 3}, // Row 0

    {4, 5, 6} // Row 1

    };

two-dimensional arrays

9
New cards
  • use nested for loops: the outer loop iterates over rows, the inner loop over columns
    for (int i = 0; i < num_rows; i++) {

    for (int j = 0; j < num_cols; j++) {

    printf("%d ", matrix[i][j]);

    }

    printf("\n"); // New line after each row

    }

processing 2D arrays

10
New cards
  • crucial: when passing a 2D array to a function, you must specify the number of columns in the function parameter, the number of rows can be omitted

  • this is because the compiler needs to know how to calculate the memory location of array[i][j] (it uses: base_address + (i num_columns + j) * sizeof(type)
    // Correct: Must specify columns

    void PrintMatrix(int mat[][3], int rows) { ... }

    // Also correct: Specify both dimensions

    void PrintMatrix(int mat[4][3], int rows) { ... }

    // INCORRECT: This will not compile

    void PrintMatrix(int mat[][], int rows, int cols) { ... }

2D arrays as function parameters

11
New cards
  • a collection of pre-written functions for common tasks

  • to use them, include the appropriate header file

  • common header files and functions:

    • <stdio.h>: printf, scanf, fopen, fclose

    • <math.h>: Mathematical functions. Requires linking with the math library (e.g., -lm on Linux/Mac, automatic in VS).

      • double sqrt(double x); // Square root

      • double pow(double x, double y); // x to the power of y

      • double sin(double x); // Sine (x in radians)

    • <stdlib.h>: rand(), srand(), malloc()

    • <string.h>: strlen(), strcpy(), strcmp() (see Chapter 7)

the C standard library

12
New cards
  • you can use libraries written by others (or yourself) that are not part of the standard library

  • this typically involves two files:

    • 1. header file (.h): contains the function prototypes (the interface)

    • 2. source file (.c): contains the function definitions (the implementation)

  • usage:

    • 1. copy both files into your project directory

    • 2. in your source code, use #include “library.h” (note the use of quotes ““ instead of angle brackets <> for non-standard libraries)

    • 3. when compiling, you must compile all source files together

      • Command Line: cl /W4 myprogram.c library.c

      • In Visual Studio: Add both .c files to your project.

external (programme-defined) libraries

13
New cards
  • The LibBMP library

    • A library provided for this course to read and write BMP image files.

    • Key Functions:

      • LoadBMPFile("input.bmp", &width, &height); // Loads an image from disk.

      • SaveBMPFile("output.bmp", width, height); // Saves the image to disk.

      • GetPixelValue(row, col, channel); // Gets the colour intensity (0-255) for a specific pixel and channel (0=Red, 1=Green, 2=Blue).

      • SetPixelValue(value, row, col, channel); // Sets the colour intensity for one channel.

      • DrawPixel(row, col, r, g, b); // A convenient function to set all three colour channels of a pixel at once.

  • The LibBMP turtle

    • A "turtle graphics" system built on top of LibBMP, inspired by the Logo programming language.

    • It simulates a turtle with a pen that moves around the image, drawing lines.

    • Key Functions:

      • StartAt(row, col);

      • PenUp(); / PenDown();

      • PenColour(r, g, b);

      • TurnLeft(angle_in_degrees); / TurnRight(angle_in_degrees);

      • Forward(distance); / Backward(distance);

what are examples of external (programmer-defined) libraries

Explore top flashcards

respiratory system
Updated 695d ago
flashcards Flashcards (22)
Exam 2 For Dorth
Updated 229d ago
flashcards Flashcards (110)
The Immune System
Updated 324d ago
flashcards Flashcards (35)
Biology Unit 7
Updated 908d ago
flashcards Flashcards (210)
religion final
Updated 887d ago
flashcards Flashcards (29)
respiratory system
Updated 695d ago
flashcards Flashcards (22)
Exam 2 For Dorth
Updated 229d ago
flashcards Flashcards (110)
The Immune System
Updated 324d ago
flashcards Flashcards (35)
Biology Unit 7
Updated 908d ago
flashcards Flashcards (210)
religion final
Updated 887d ago
flashcards Flashcards (29)