Summary
Continuation of review of C. Pointer arithmetic. void* pointers. The array-pointer pun. Dynamic memory allocation. Interpreting complex declarations. Dynamic allocation of multidimensional arrays. Structures and pointers. Typedefs.
C Part 2 Slides: 04_c_part2.pdf
Videos
Code Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <stdio.h> /* assigns val to p[i], ..., p[i+n-1] */ void set_range(int *p, int n, int val) { for (int i=0; i<n; i++) p[i] = val; } /* prints p[0], ..., p[n-1] */ void print(int *p, int n) { for (int i=0; i<n; i++) printf("%d ", p[i]); printf("\n"); } int main() { int a[10]; set_range(&a[0], 10, 0); // a[0..9]=0 print(&a[0], 10); set_range(&a[3], 5, 8); // a[3..7]=8 print(&a[0], 10); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <assert.h> int main() { int x = 5; int *p = &x; double y = 3.1415; double *q = &y; void *r; r = p; // conversion from int* to void* p = r; // conversion back to int* assert(*p == 5); r = q; // conversion from double* to void* q = r; // conversion back to double* assert(*q == 3.1415); } |
1 2 3 4 5 6 7 8 |
#include <assert.h> int main() { int a[10]; int *p; p = a; // same as p=&a[0] assert(a[3] == *(p+3)); assert(a[3] == *(a+3)); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <stdlib.h> #include <assert.h> #include <stdio.h> void print(int *p, int n) { for (int i=0; i<n; i++) printf("%d ", p[i]); printf("\n"); } int main(int argc, char * argv[]) { int n = atoi(argv[1]); // converts first command-line arg to int int * p = malloc(n*sizeof(int)); assert(p); // check that malloc succeeded for (int i=0; i<n; i++) p[i] = i; print(p, n); free(p); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <stdlib.h> #include <stdio.h> #include <assert.h> double ** create_2d(int n, int m) { double * storage = malloc(n*m*sizeof(double)); assert(storage); double ** rows = malloc(n*sizeof(double*)); assert(rows); for (int i=0; i<n; i++) rows[i] = &storage[i*m]; return rows; } void destroy_2d(double ** a) { free(a[0]); // free storage free(a); // free rows } int main(int argc, char * argv[]) { int n = atoi(argv[1]), m = atoi(argv[2]); double ** a = create_2d(n, m); for (int i=0; i<n; i++) for (int j=0; j<m; j++) a[i][j] = 100*i + j; for (int i=0; i<n; i++) { for (int j=0; j<m; j++) printf("%7.1lf ", a[i][j]); printf("\n"); } destroy_2d(a); } |