c语言基本操作
常量(不可修改)
#define name 12
const int name = 12
函数分文件编写
- 创建后缀.h头文件
- 创建.cpp源文件
- 头文件写函数声明
- 源文件写函数定义
//源文件cpp内写定义:
#include <iostream>
#include "myfunction.h" //双引号表示自定义 和头文件关联起来
using namespace std;
void swap(int a,int b){
//函数体
}
//头文件创建myfunction.h:
void swap(int a,int b);
//main.app内:
#include "swap.h"
指针
-
指针在32位下都是4字节空间,都是地址
-
空指针:指向地址编号为零的指针null
-
野指针:非法越界
//基本使用 int a = 10; int *p = &a; //空指针(null要大写NULL) int * p = NULL;
-
const修饰指针
- 常量指针:const修饰指针
- 指针常量:const修饰常量
- const修饰指针和常量
//常量指针 指向可以修改,值不能修改 const int *p = &a; //指针常量 值可以修改,指向不能修改 int * const p = &a; //指向常量的指针常量 const int * const p = &a;
记忆技巧:看const后面紧跟限定什么,什么就不能改
const int *p = &a;
const后面紧跟*那就不能修改对应的值int * const p = &a;
const后面紧跟p指针,那就不能修改对应指向
结构体
-
定义和使用(创建可以省略struct,定义使用不能省略)
struct student{ string name; int age; int score; } //方式一 struct student s1; s1.name="xx" //方式二 struct student s1={...}; //方式三 struct student{ string name; int age; int score; }s3;//顺便创建结构体变量
-
结构体数组
struct student myarray[]={ {"张三",19,99}, {"张3",12,29}, {"张5",19,39}, }
-
使用const可以防止误操作,在函数内将形参变成指针,可以避免创建一个新对象,节省空间,但是会误修改,所以使用常量指针
void printfstudent(const student *s){ //有修改的时候就会报错, }