daily notes[27]
C语言中的数组是有序集合,支持索引访问,元素可以是内置类型、复合类型或数组类型。二维数组按行存储,可通过嵌套花括号初始化。数组可作为函数参数传递,但需要指定列
·
文章目录
array
- the array in C language actually is a sorted collection ,which can be indexed, every element only belong to each one of C Data types including compound type, Built-in type,even array type.
// 声明一个3行4列的二维数组
int matrix1[3][4];
// 初始化二维数组
int matrix1[2][3] = {
{1, 2, 3}, // 第0行
{4, 5, 6} // 第1行
};
// 也可以省略第一维大小,由编译器推断
int matrix2[][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
int val = matrix2[1][2]; // 访问第1行第2列的元素(值为6)
matrix2[0][1] = 10; // 修改第0行第1列的元素
to save elements is in a row-by-row for multi-dimensional array.
matrix[0][0], matrix[0][1], matrix[0][2]
matrix[1][0], matrix[1][1], matrix[1][2]
....
the array can be parameter of a function shown as follows.
void printMatrix(int arr[][3], int rows) {
for(int i=0; i<rows; i++) {
for(int j=0; j<3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
the pointer to an array used to manipulate elements of the array more flexibly .
int matrix[2][3] = {
{1, 2, 3}, // 第0行
{4, 5, 6} // 第1行
};
int (*ptr)[3] = matrix; // ptr是指向含有3个int元素的数组的指针
printf("%d", ptr[1][2]); // 等同于matrix[1][2]
by the way,the multi-dementional array can be dynamically created.
int rows = 3, cols = 4;
int **arr = (int **)malloc(rows * sizeof(int *));
for(int i=0; i<rows; i++) {
arr[i] = (int *)malloc(cols * sizeof(int));
}
getchar() and putchar() in C
getchar()receive a single character from standard input.
int getchar(void);
putchar()output a single character to standard output
int putchar(int c);
#include <stdio.h>
int main() {
int c;
printf("Type some text (press Ctrl+D/Ctrl+Z to end):\n");
// Read characters until EOF
while ((c = getchar()) != EOF) {
// Write each character back
putchar(c);
}
return 0;
}
The ctype.h Header in C
this header file create a lot of functions to handle character.
isalpha(c) - Checks if c is an alphabetic letter (a-z, A-Z)
isupper(c) - Checks if c is an uppercase letter
islower(c) - Checks if c is a lowercase letter
isdigit(c) - Checks if c is a decimal digit (0-9)
isxdigit(c) - Checks if c is a hexadecimal digit (0-9, a-f, A-F)
isspace(c) - Checks if c is a whitespace character (space, \t, \n, etc.)
#include <stdio.h>
#include <ctype.h>
int main() {
char c;
printf("Enter a character: ");
c = getchar();
if (isalpha(c)) {
printf("'%c' is a letter\n", c);
printf("Uppercase: %c\n", toupper(c));
printf("Lowercase: %c\n", tolower(c));
}
else if (isdigit(c)) {
printf("'%c' is a digit\n", c);
}
else if (isspace(c)) {
printf("You entered whitespace\n");
}
else {
printf("'%c' is something else\n", c);
}
return 0;
}
logical operations
- there are three logical operator in C language that are
&&which means and,||which means or,!which means not.
- Logical AND (
&&)
Returns true (1) only if both operands are true
Example: (a > b) && (c != d)
- Logical OR (
||)
Returns true (1) if either operand is true
Example: (x == y) || (z < 0)
- Logical NOT (
!)
Inverts the truth value (true becomes false, false becomes true)
Example: !(flag)
static
- static variable,which are initialized only once, survived in the memory regardless of the scope of variable .
#include <stdio.h>
void counter() {
static int count = 0; // Static variable
count++;
printf("Count: %d\n", count);
}
int main() {
counter(); // Output: Count: 1
counter(); // Output: Count: 2
counter(); // Output: Count: 3
return 0;
}
staticembellishes a global variable or function and restricts its visibility to the current file.
// File: file1.c
static int hiddenVar = 42; // Only visible in file1.c
void printHidden() {
printf("%d\n", hiddenVar); // Works
}
// File: file2.c
extern int hiddenVar; // ERROR: Cannot access hiddenVar from file1.c
// File: utils.c
static void helper() { // Only visible in utils.c
printf("Helper function\n");
}
void publicFunc() {
helper(); // OK
}
// File: main.c
extern void helper(); // ERROR: Cannot call helper() from another file
malloc
mallocasks for memory allocation from OS,freereleases the part of memory which was distributed bymalloc.
#include <stdint.h> // 使用标准整数类型
// 定义消息类型(可根据需求扩展)
typedef enum {
MSG_TYPE_UNKNOWN = 0,
MSG_TYPE_COMMAND,
MSG_TYPE_DATA,
MSG_TYPE_ACK,
MSG_TYPE_ERROR
} MessageType;
// 定义消息头(固定部分)
typedef struct {
uint32_t type; // 消息类型(如命令、数据、ACK等)
uint32_t length; // 消息体的长度(字节数)
uint64_t timestamp; // 可选:时间戳
uint32_t checksum; // 可选:校验和(用于数据完整性验证)
} MessageHeader;
// 定义完整消息结构(头 + 变长数据)
typedef struct {
MessageHeader header; // 消息头
char payload[]; // 柔性数组(C99),存储实际数据(长度由 header.length 决定)
} Message;
#include <string.h>
#include <stdio.h>
// 动态创建消息(需手动管理内存)
Message* create_message(MessageType type, const char* data, uint32_t data_len) {
// 分配内存(消息头 + 实际数据)
Message* msg = malloc(sizeof(MessageHeader) + data_len);
if (!msg) return NULL;
// 填充消息头
msg->header.type = type;
msg->header.length = data_len;
msg->header.timestamp = time(NULL); // 假设有 time() 函数
msg->header.checksum = 0; // 简化的示例,实际应计算校验和
// 拷贝数据到 payload
memcpy(msg->payload, data, data_len);
return msg;
}
// 示例:发送一条命令消息
int main() {
const char* cmd = "START_SERVER";
Message* msg = create_message(MSG_TYPE_COMMAND, cmd, strlen(cmd) + 1);
if (msg) {
printf("Message created: type=%d, length=%d\n",
msg->header.type, msg->header.length);
free(msg); // 释放内存
}
return 0;
}
how to handle file
- to manipulate files involves opening, reading, writing, and closing files.
File Modes
Mode Description
"r" Read (file must exist)
"w" Write (creates/overwrites file)
"a" Append (creates/appends to file)
"r+" Read/Write (file must exist)
"w+" Read/Write (creates/overwrites)
"a+" Read/Append (creates/appends)
"b" Binary mode (e.g., "rb", "wb")
Function Usage
fopen() Open a file
fclose() Close a file
fprintf() Write formatted text
fscanf() Read formatted text
fgetc() Read a character
fputc() Write a character
fgets() Read a line
fputs() Write a string
fread() Read binary data
fwrite() Write binary data
feof() Check end-of-file
ferror() Check file errors
#include <stdio.h>
typedef struct {
int id;
char name[50];
float score;
} Student;
int main() {
// Write binary data
Student s1 = {1, "Alice", 95.5};
FILE *file = fopen("students.dat", "wb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
fwrite(&s1, sizeof(Student), 1, file);
fclose(file);
// Read binary data
Student s2;
file = fopen("students.dat", "rb");
fread(&s2, sizeof(Student), 1, file);
printf("ID: %d, Name: %s, Score: %.2f\n", s2.id, s2.name, s2.score);
fclose(file);
return 0;
}
references
deepseek
更多推荐


所有评论(0)