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 | #include <stdio.h>
#include <stdlib.h>
// malloc(…) allocates memory (i.e., reserves space) on the HEAP for
// whatever you want to store. Unlike arrays on the stack, you specify
// the "buffer size" (i.e., amount of memory) at runtime (i.e., with a
// variable while the program is running).
//
// malloc(«number of bytes») → returns the address of the first byte in
// the newly allocated buffer (your new space).
//
// Use this form:
// «TYPE»* «VARIABLE» = malloc(«num of elements» * sizeof(*«VARIABLE»));
// ∙ Do not use a cast.
// ∙ Do not use sizeof(«TYPE»). Use sizeof(*«VARIABLE») instead.
// Use sizeof(*«VARIABLE») instead.
// Use sizeof(*«VARIABLE») instead.
// … because *«VARIABLE» is of type «TYPE»
//
// DO NOT USE CODE LIKE THIS:
// char* s = malloc(4); // use sizeof(…)
// char* s = malloc(4 * sizeof(int)); // use sizeof(*«variable») ← GOOD
// // not sizeof(«type») ← BAD
// With malloc(…) you can decide your needs at runtime.
// space does not go away after the function returns.
//
// You MUST free(…) the space using free(«address»).
//
// free(…) must be called EXACTLY once for each call to malloc(…).
//
// free(…) takes the address that malloc(…) returned.
int main(int argc, char* argv[]) {
int* a_n = malloc(sizeof(*a_n));
// Allocate space for one int on the HEAP.
*a_n = 20;
// "LOCATION A"
printf("*a_n = %d\n", *a_n); // log_int(*a_n)
printf(" a_n = %p\n", (void*)a_n); // log_addr(a_n)
free(a_n);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.