Sub topic 1
Data Types, Sizes, and Addresses in C
Prerequisites
This chapter assumes you know basic C syntax (variables, functions, and loops), binary and hexadecimal numbers, and how to compile a small program with gcc or clang.
Data Types and Sizes
Each variable has a type, and the type sets how many bytes the variable occupies. Sizes are implementation-defined. On most 64-bit systems int is 4 bytes and a pointer is 8 bytes, but you should check with sizeof rather than assume.
#include <stdio.h>
int main(void) {
int n = 42;
printf("%zu %p\n", sizeof n, (void *)&n);
return 0;
}Storage Classes, Scope, and Lifetime
Scope is where a name is visible. Lifetime is how long the object exists. A local variable lives until its block ends. A static local keeps its value between calls, and a global lives for the whole program.
Pointer Basics
A pointer stores an address. The & operator takes an address, and * reads or writes the value at that address.
int x = 5;
int *p = &x;
*p = 7; /* x is now 7 */Pass by Value and Pass by Pointer
C always passes arguments by value. A function receives a copy. To let a function change the caller's variable, pass its address.
#include <stdio.h>
void swap(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int main(void) {
int a = 1, b = 2;
swap(&a, &b);
printf("%d %d\n", a, b);
return 0;
}This prints 2 1.
Pointer Arithmetic
Adding 1 to an int * moves the pointer by sizeof(int) bytes, which is one element. Subtracting two pointers into the same array gives the number of elements between them.
#include <stdio.h>
int main(void) {
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d\n", *(p + 2));
return 0;
}This prints 30.
Arrays and Pointers: Decay and sizeof
In most expressions, an array name decays to a pointer to its first element. sizeof is the exception. Applied to an array in the scope that declared it, sizeof returns the total byte count. A parameter declared as int arr[] is really an int *, so sizeof arr inside that function returns the pointer size.
#include <stdio.h>
void f(int arr[]) {
printf("%zu\n", sizeof arr);
}
int main(void) {
int a[10];
printf("%zu\n", sizeof a);
f(a);
return 0;
}On a typical 64-bit system this prints 40, then 8.
Exercise
In main, int a[10]; and sizeof a gives 40. If f(a) receives the array and computes sizeof arr, what does it print on a 64-bit system, and why?
Show answer
It prints 8. The parameter int arr[] is adjusted to int *, so sizeof returns the size of a pointer, not the array.