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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
// Short demo of various uses of pointers. #include <stdio.h> #include <stdlib.h> #include <string.h> struct student{ char fname[25]; int id, age; }; // i is copied in to the function, then copied back out. int stackCopy(int i){ i = i+1; return i; } // s is copied in to the function, then copied back out. struct student stackCopy2(struct student s){ s.id = 801; return s; } void pointerDirecting(){ int i = 55; int *pi = &i; int *qi = &i; i = 42; printf("pointerDirecting Out: pi: %d qi: %d\n", *pi, *qi); } void pointerDirecting2(){ int i = 42; int *pi; pi = &i; printf("pointerDirecting2 Out: pi: %d\n", *pi); } // Don't do this! int* stackPointer(){ int i = 5; return &i; // i is allocated on the stack, and will be destroyed when this function exits! } int* heapPointer(){ int *ptr; ptr = (int*)malloc(sizeof(int)); // Allocate on heap. *ptr = 42; return ptr; } struct student* createNewStudent(){ struct student *newstudent = malloc(sizeof(struct student)); strcpy((*newstudent).fname, "Jon"); newstudent->id = 800; newstudent->age = 22; return newstudent; } // Strings are arrays, and an array cannot be returned, so one option is to // place it on the heap and return a pointer. char* arrayPointer(int n){ char *str = malloc(sizeof(char) * (n + 1)); for (int i = 0; i < n; i++){ str[i] = 'n'; } str[n] = '\0'; return str; } // Or use what we'll eventually refer to as an "in-out" parameter. void arrayPointer2(char* str, int n){ for (int i = 0; i < n; i++){ str[i] = 'n'; } str[n] = '\0'; } int main(){ int i = 12; printf("i %d, stackCopy i: %d\n", i, stackCopy(i)); struct student s1; s1.id = 800; printf("s1's id: %d\n", s1.id); struct student s2 = stackCopy2(s1); printf("s1's id: %d\n", s1.id); printf("s2's id: %d\n", s2.id); pointerDirecting(); pointerDirecting2(); // stackPointer(); printf("heapPointer Out: %d\n", *heapPointer()); printf("new student first name: %s\n", createNewStudent()->fname); printf("string of length 5: %s\n", arrayPointer(5)); // Allocate a new string of length 5: char *str = malloc(sizeof(char) * (6)); arrayPointer2(str, 5); printf("string of length 5: %s\n", str); } // Output: //i 12, stackCopy i: 13 //s1's id: 800 //s1's id: 800 //s2's id: 801 //pointerDirecting Out: pi: 42 qi: 42 //pointerDirecting2 Out: pi: 42 //heapPointer Out: 42 //new student first name: Jon //string of length 5: nnnnn //string of length 5: nnnnn |