Worksheet: pointers, addresses, memory
Nothing to hand in.
- What does this function do? What kind of drawing would you
make to help explain it to somebody?
int dosomething(char *a, char *b) { assert(a != NULL && b != NULL); while (*a == *b && *a != '\0') { a++; b++; } return (int)(*a) - (int)(*b); } int main() { char s[] = "horse"; char t[] = "cow"; int n = dosomething(s, t); printf("%d\n", n); n = dosomething("pig", "piglet"); printf("%d\n", n); return 0; }
- What does this weird code print, and why?
int x = 0x00434241; char *p = (char *)(&x); printf("%s\n", p);
- Another bit of weird code. What do you get here, and why?
int a[8] = {1, 1, 2, 3, 5, 8, 13, 21}; int *p1 = a; int *p2 = a; p2++; p2++; p2++; p2++; printf("A: %d\n", *p1); printf("B: %d\n", *p2); printf("C: %d\n", (int)(p2 - p1)); printf("D: %ld\n", (long)(p2) - (long)(p1));
- What is this code trying to do? Also, something is wrong with this code: what is it?
char **f(int n, int m) { char **a = malloc(n * sizeof(char *)); if (a == NULL) { return NULL; } for (int k = 0; k < n; k++) { a[k] = malloc((m + 1) * sizeof(char)); if (a[k] == NULL) { return NULL; } } return a; }
- What output do you expect from this code, and why?
Note that
%luprints "unsigned long" integers (which is what bothsizeofandstrlenreturn) in decimal.char s1[] = "Hello"; char *s2 = "Hello"; printf("%lu, %lu\n", sizeof(s1), strlen(s1)); printf("%lu, %lu\n", sizeof(s2), strlen(s2)); - In what ways are these three declarations the same, and
in what ways are they different?
char s1[10] = "moose"; char s2[] = "otter"; char *s3 = "marmot";