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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
int main(int argc, char* argv[]) {
int numbers_on_stack[] = { 10, 11, 12 };
// (gdb) whatis numbers_on_stack
// type = int[3]
//
// REASON: int numbers_on_stack[] = { 10, 11, 12 };
// ... is equivalent to
// int numbers_on_stack[3] = { 10, 11, 12 };
//
// (gdb) p sizeof(numbers_on_stack)
// $1 = 12
//
// REASON: 4 bytes per int x 3 ints per int[3] = 12 bytes per int[3]
//
// If variable is on the stack (i.e., declared using square brackets), then
// sizeof will give you the size of one element times the number of elements.
//
// sizeof(numbers_on_stack) because
// - numbers_on_stack is type int[4]
// - each element (such as numbers_on_stack[0]) is type int.
// - int consumes 4 bytes each (on our platform)
// - there are 3 elements
// - 4 bytes per int x 3 ints per int[4] = 12 bytes
//
// SUMMARY: sizeof(«array on the stack») is different from sizeof(«address»).
// Look at how the variable was declared.
int* a_first_number = &(numbers_on_stack[0]);
int* numbers_on_heap = malloc(3 * sizeof(*numbers_on_heap));
numbers_on_heap[0] = 10;
numbers_on_heap[1] = 11;
numbers_on_heap[2] = 12;
free(numbers_on_heap);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.