Different data types and how to initialize them
different data types and how to initialize them
Different data types and how to initialize them
Let me break down the different data types and how to initialize them with simple mental models and code snippets.
1. Normal Variables
Think of them as boxes holding values.
1
2
3
int a = 10; // integer
float f = 3.14; // float
char c = 'A'; // single character
2. Arrays
An array is a collection of boxes of the same type, placed in sequence.
1
2
3
int arr[5] = {1, 2, 3, 4, 5}; // integer array
char str1[] = "Hello"; // string as char array (null-terminated)
char str2[6] = {'H','e','l','l','o','\0'}; // same thing explicitly
Rule: If you don’t fully fill an array, remaining elements are 0.
1
int arr2[5] = {1,2}; // arr2 = {1,2,0,0,0}
3. Pointers
A pointer is a box that stores the address of another box.
1
2
3
int x = 10;
int *p = &x; // pointer to int
printf("%d", *p); // dereference → prints 10
Trick:
&= “address of”*= “value at that address”
4. Pointer + Array
Arrays and pointers are closely related.
1
2
3
4
int arr[3] = {10,20,30};
int *p = arr; // points to arr[0]
printf("%d", *(p+1)); // prints 20
5. Strings (char arrays vs pointers)
1
2
char str1[] = "Hello"; // stored in modifiable array
char *str2 = "Hello"; // stored in read-only memory (can’t change chars)
6. Structs
A struct is a custom data type grouping multiple variables.
1
2
3
4
5
6
struct Point {
int x;
int y;
};
struct Point p1 = {10, 20}; // initialize
With pointers:
1
2
3
struct Point p2 = {30, 40};
struct Point *ptr = &p2;
printf("%d", ptr->x); // prints 30
Mental model:
- Normal variable → box with value
- Array → row of boxes
- Pointer → box with an arrow to another box
- String → char array ending with
'\0' - Struct → box containing multiple labeled smaller boxes
This post is licensed under CC BY 4.0 by the author.
