#include #include void swap(int* a, int* b){ int c = *a; *a = *b; *b = c; } void bubble_sort(int *tosort, int len){ char finished = 0; while(!finished){ finished = 1; for(int i = 0; i < len-1; i++) if(tosort[i] > tosort[i+1]){ swap(tosort+i, tosort+i+1); finished = 0; } } } void print_array(int *toprint, int len){ printf("{"); for(int *item = toprint; item < toprint+len; ++item) if(toprint + len == item + 1) printf("%d", *item); else printf("%d,", *item); printf("}"); } int main(){ int a = 10; int *pa; // Stands for "pointer to a" pa = &a; // &a means "the memory address of a" printf("a = %d\n", a); *pa = 22; // *pa means "the thing pa points to" // Alternative explanation: "The thing at memory address pa" printf("a = %d\n", a); printf("a = %d (the thing that pa points to is %d)\n", *pa, *pa); printf("pa = %lx\n", pa); // lx: 64-bit unsigned in hex int b = 42; pa = &b; printf("b = %d (the thing that pa points to is %d)\n", *pa, *pa); printf("pa = %lx\n", pa); // lx: 64-bit unsigned in hex printf("&pa (memory address of pa) = %lx\n", &pa); // Pointers are the same as a size_t, but the compiler likes to know what they point to int array[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90}; array[5] = 100; // You can do this *(array+5) = 100; // Another way of saying it! /* // Causes bad behaviour, but NO warnings OR exceptions for(int i = 0; i < 100; i++){ printf("Overwriting array[%d]\n", i); array[i] = 100; } */ // Standard way to print out everything in an array: for(int i = 0; i < 10; i++) // i++ happens at the end printf("Item %d is %d\n", i, array[i]); // i++ happens here // Alternative way using pointers for(int *item = array; item < array+10; item++) printf("%d\n", *item); // Silly short alternative: for(int *item = array; item < array+10; printf("%d\n", *(item++))) ; int *bob = array; bob[9] = 231; printf("array[9] = %d\n", array[9]); // Non-initialized array int fred[16]; fred[15] = 22; // fred[0] through fred[14] are uninitialized (contain random values) printf("fred[14] = %d\n", fred[14]); int t; printf("t = %d\n", t); int ** ppa = &pa; // Pointer to the pointer we made earlier that points to b now **ppa = 7; printf("*pa = %d\n", *pa); *ppa = array+3; printf("*pa = %d\n", *pa); print_array(array, 10); printf("\n"); print_array(fred, 16); printf("\n"); bubble_sort(array, 10); print_array(array, 10); printf("\n"); // An array on the heap! 32 integers. int *heap_array = (int*)malloc(32 * sizeof(int)); for(int* item = heap_array; item < heap_array + 32; item++) *item = (size_t)item % 1024; print_array(heap_array, 32); free(heap_array); return 0; }