数据类型详解
学习目标
通过本集的学习,你将能够:
- 理解基本数据类型
- 掌握复合数据类型
- 学会使用数组
- 理解记录(结构体)
1. 基本类型
1.1 数值类型
整数类型:
- byte, short, int, long(Java)
- i8, i16, i32, i64(Rust)
- int(Python, 任意精度)
浮点数类型:
- float, double(Java, C++)
- f32, f64(Rust)
- float(Python)1.2 布尔类型
布尔类型:
- bool: true, false
示例:
flag = true
condition = 5 > 3 // true1.3 字符类型
字符类型:
- char(Java, C++)
- char(Rust, Unicode)
示例:
c = 'A'1.4 字符串类型
字符串类型:
- String(Java, Rust)
- str(Rust, 字符串切片)
- str(Python)
示例:
s = "Hello, World!"2. 复合类型
2.1 什么是复合类型?
复合类型由多个值组成。
复合类型:
- 数组/列表
- 结构体/记录
- 元组
- 枚举
- 联合3. 数组
3.1 什么是数组?
数组是相同类型元素的有序集合。
数组特点:
- 固定大小
- 相同类型
- 连续内存
- 随机访问 O(1)3.2 数组声明
C++ 数组:
int arr[5]; // 声明
int arr[] = {1, 2, 3, 4, 5}; // 初始化
Java 数组:
int[] arr = new int[5];
int[] arr = {1, 2, 3, 4, 5};
Python 列表:
arr = [1, 2, 3, 4, 5] // 动态大小3.3 数组访问
访问元素:
arr[0] // 第一个元素
arr[1] // 第二个元素
索引从 0 开始!
内存布局:
地址: 100 104 108 112 116
值: 1 2 3 4 5
索引: 0 1 2 3 43.4 多维数组
二维数组:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
访问:
matrix[0][0] // 1
matrix[1][2] // 6
Python:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]4. 记录(结构体)
4.1 什么是记录?
记录(结构体)是不同类型字段的集合。
结构体特点:
- 不同类型
- 命名字段
- 连续内存(通常)4.2 结构体声明
C++ 结构体:
struct Point {
int x;
int y;
};
Point p;
p.x = 10;
p.y = 20;
Rust 结构体:
struct Point {
x: i32,
y: i32,
}
let p = Point { x: 10, y: 20 };
Python 类:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(10, 20)4.3 内存布局
struct Point {
int x; // 4 bytes
int y; // 4 bytes
};
总大小:8 bytes
内存布局:
地址: 100 104
字段: x y
值: 10 205. 实用案例
5.1 案例1:数组求和
def sum_array(arr):
total = 0
for x in arr:
total += x
return total
arr = [1, 2, 3, 4, 5]
print(sum_array(arr)) // 155.2 案例2:结构体表示学生
struct Student {
char name[50];
int id;
float gpa;
};
struct Student s;
strcpy(s.name, "Alice");
s.id = 12345;
s.gpa = 3.8;6. 自测问题
- 基本类型有哪些?
- 数组和结构体的区别是什么?
- 数组索引从几开始?
- 什么是多维数组?
- 结构体的优点是什么?
7. 下集预告
下一集我们将学习指针与引用!
参考资料
- 《程序设计语言:概念与构造》
- 《编程语言原理》