Wednesday's Lecture
Arrays, Pointers, and Strings
portal.c
// Pointers are like wormholes...
// Where does a lecture on wormholes go? In one ear, and out the other.
//
// At Aperture Laboratories, we have developed a specialised utility,
// a pointer gun. It has two settings, `*` and `&`.
//
// 2017-08-23 Jashank Jeremy <{jashankj,z5017851}@cse.unsw.edu.au>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int b = 1645;
printf ("b = %d\n", b);
int *pb;
pb = &b;
printf ("&b = %p\n", &b);
printf ("pb = %p\n", pb);
printf ("*pb = %d\n", *pb);
*pb = 1647;
printf ("*pb = %d\n", *pb);
printf ("b = %d\n", b);
int **ppb = &pb;
**ppb = 1711;
printf ("ppb = %p\n", ppb);
printf ("*ppb = %p\n", *ppb);
printf ("pb = %p\n", pb);
printf ("**ppb = %d\n", **ppb);
printf ("b = %d\n", b);
return EXIT_SUCCESS;
}
showCharArray.c
// Show a character array.
// 2017-08-23 Jashank Jeremy <{jashankj,z5017851}@cse.unsw.edu.au>
#include <stdio.h>
#include <stdlib.h>
void showCharArray (char *array);
int main (int argc, char *argv[]) {
//char *str = {'A', 'N', 'D', 'R', 'E', 'W', '\0'};
char *str = "ANDREW";
printf ("%s\n", str);
return EXIT_SUCCESS;
}
void showCharArray (char *array) {
int index = 0;
while (array[index] != '\0') {
putchar (array[index]);
index++;
}
}
strmem.c
// Modifying a string literal is potentially lethal.
// 2017-08-23 Jashank Jeremy <{jashankj,z5017851}@cse.unsw.edu.au>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
/// If I declare the following:
//
// char *str = "It's currently 5:00 pm.";
//
/// ... and attempt to change a value in it:
//
// str[17] = '5';
//
/// ... our program will be shot down with the dreaded segmentation
/// fault, a memory access error. 'dcc' shows "ASAN:DEADLYSIGNAL".
char str[] = "It's currently 5:00 pm.";
// char str[] = {'I', 't', '\'', 's', ..., '\0'};
char *strA = str;
printf ("str = %p\n", str);
strA[17] = '5';
printf ("%s\n", str);
return EXIT_SUCCESS;
}