← again tap: answer good → ↑ swipe up at the end: next
Question
What are the basic scalar data types in C?
Answer
Three families: integer types (char/short/int/long/long long, signed or unsigned), floating-point (float/double/long double), and pointers.
Integer types:
// 1 byte, often used for characters
char c;
// At least 2 bytes
short int s;
// At least 2 bytes (usually 4)
int i;
// At least 4 bytes
long int l;
// At least 8 bytes (C99)
long long int ll;
Signed vs unsigned:
// Can be negative (default)
signed int si;
// 0 or positive only
unsigned int ui;
// 0-255
unsigned char uc;
Floating-point:
// ~7 decimal digits precision
float f;
// ~15 decimal digits precision
double d;
// Extended precision
long double ld;
Pointers:
// Pointer to int
int *p;
// Pointer to pointer to pointer to char
char ***c;
Read pointer declarations right-to-left:
int *p→ "p is a pointer to int"char **argv→ "argv is a pointer to pointer to char"
Tip: Use https://cdecl.org/ to decode complex C declarations!
Go deeper:
C data types — Wikipedia — the arithmetic types and their size guarantees.
Question
How do arrays work in C, and why are they "really just pointers"?
Answer
An array is just a block of contiguous elements, and a[i] is pure syntactic sugar for *(a + i) — C "doesn't really know" arrays, only pointers.
// Array of 10 ints
int a[10];
// Set second element
a[1] = 5;
// 2D array
int pixel[1024][768];
pixel[0][0] = red;
Arrays ARE pointers:
int a[10];
// Array name IS the address of first element
int *p = a;
// These are IDENTICAL:
a[1] = 5;
// Pointer arithmetic
*(a + 1) = 5;
// In fact, even this works:
// Because a[1] == *(a+1) == *(1+a) == 1[a]
1[a] = 5;
No bounds checking!
int a[10];
// Compiles fine! Undefined behavior at runtime.
a[100] = 5;
// Also "works" - accesses memory before array
a[-1] = 5;
Function parameters - arrays decay to pointers:
// These are
void foo(int *a, int b[]);
// ALL identical!
void foo(int a[], int *b);
// These are
int main(int argc, char **argv);
// equivalent!
int main(int argc, char *argv[]);
Security implication: Buffer overflows happen because C doesn't check array bounds!