一.const 关键字的使用
在 C 语言中,const 关键字用于定义常量,表示该变量的值在初始化后不能被修改。它可以用来保护数据,增强代码的可读性和安全性:
1. 定义常量
使用 const 可以定义一个常量,这个常量的值在程序运行期间不能被改变。
#include <stdio.h>
int main() {
const int x = 10;
// x = 20;
printf("%d\n", x);
return 0;
}
2. 指针和 const
const 可以与指针结合使用,表示指针指向的值不能被修改,或者指针本身不能被修改。
指向常量的指针
#include <stdio.h>
int main() {
const int value = 10;
const int *ptr = &value;
// *ptr = 20; // 错误:试图修改常量
printf("%d\n", *ptr);
return 0;
}
常量指针
#include <stdio.h>
int main() {
int value = 10;
int *const ptr = &value;
*ptr = 20; // 合法:可以通过指针修改 value 的值
// ptr = NULL; // 错误:试图修改指针本身
printf("%d\n", *ptr);
return 0;
}
3. 常量数组
可以定义一个常量数组,表示数组的内容不能被修改。
#include <stdio.h>
int main() {
const int arr[] = {1, 2, 3, 4, 5};
// arr[0] = 10; // 错误:试图修改常量数组的元素
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
4. 函数参数
在函数参数中使用 const 可以保护传入的参数不被修改
#include <stdio.h>
void printArray(const int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
const 的使用 能写成const的都写成const;
二.指针操作一维字符型数组
指针 + 字符串
字符串 // 在c语言中是按照字符数组的形式存储
// 字符串常量 --- 存储在字符串常量区
处理字符串:
char s[] = "hello"; //表示 在栈上开辟一块空间,用字符串常量中的 "hello"
//进行初始化
const char *p = "hello"; //表示 p指向了 字符串常量区中的 "hello"
//因为 是指向了字符串常量区
//只能做读取操作,不能修改
指针操作一维字符型数组实例:
1. gets()函数的实现:
2.strlen()函数的实现:
3.strcpy函数的实现:
4.strncpy函数的实现:
5.strncat函数的实现:
6.strcmp函数的实现:
7.strncmp函数的实现: