// Pantea Aria // static memories - they get released once the program finishes. // you can allocate memory whenever you want and free that whenver you want - Dynamic memory // malloc to allocate dynamic memory #include #include #include struct student { int zid; double marks; }; struct point { int x, y; }; int main(void) { // grab dynamic memory for one integer // allocating 4 bytes of heap and return the address into p from stack memory int *p = malloc(sizeof(int)); // assign 20 to that memory from head // dereferencing *p = 20; // print the value in the memory printf("the value is %d\n", *p); //20 // if you don't need that memory, then release it free(p); // *p = 90; // INVALID // dynamic array of int // 10 integer after each other in heap p = malloc(10 * sizeof(int)); // assign 10 to 19 to them for(int i = 10; i < 20; i++) { p[i - 10] = i; } // print out all values in the array int i = 0; while (i < 10) { printf ("%d ", p[i]); i++; } free(p); // dynamic structure from heap // define struct student before main // allocate memory from heap for 1 student struct student *q = malloc(sizeof(struct student)); // assign value to zid - dereferencing a pointer to structure q->zid = 123456; // assign value to marks q->marks = 56.6; // print out the values printf("%d %lf", q->zid, q->marks); // release it free(q); // allocate memory for one character char *ch = malloc(sizeof(char)); // assign some value to it *ch = 'A'; // check if upper or lowercase and print out if (isupper(*ch)) { printf("\n%c is upper\n", *ch); } else { printf("\n%c is lower", *ch); } free(ch); // dynamic structure // struct point - create a dynamic point (x, y) with a function, struct point *st = malloc(sizeof(struct point)); // print x, y with another function st->x = 10; st->y = 9; printf("x and y are %d and %d\n", st->x, st->y); free (st); // allocate memory for 5 points st = malloc(5 * sizeof(struct point)); if (st == NULL) { return 1; } st[0].x = 8; st[0].y = 0; // have a loop st[i].x , .... return 0; }