1 指针
int i; 定义整型变量 i。
int *p; p为指向整型数据的指针变量。
int a[n]; 定义整型数组a,它有n个元素。
int *p[n]; 定义指针数组p,它由n个指向整型数据的指针元素组成。
int (*p)[n]; p为指向含n个元素的一维数组的指针变量。
int f(); f 为一个返回整型的函数。
int *p(); p为一个返回指针的函数,该指针指向整型数据。
int (*p)(); p为指向函数的指针,该函数返回一个整型值。
int **p; p是一个指针变量,它又指向另外一个指针变量,该指针变量指向整型数据。
指针的长度在一个系统中是固定的 32位系统中是4
2 指针与数组
int a[2][3]={{1,2,3},{4,5,6}};
2.1 数组名为a 数组名a的值是一个指针常量 类型是指向元素类型的指针 一维数组指向第一个元素 多维数组 指向第一个数组 详细解释在<c和指针>数组-一维数组-数组名 多维数组-数组名
2.2 遍历数组
int main(){
int a[2][3]={{1,2,3},{4,5,6}};
int j,i=0;
for(;i<2;i++){
for(j=0;j<3;j++)
printf("==>%d\n",*(*(a+i)+j)); //a[i][j]=>*(a[i]+j)=>*(*(a+i)+j) a是指向二维数组中的第一个数组 a+1指向第二个数组
}
//第二种遍历方式
//获得数组长度的常用方法
int len=sizeof(a)/sizeof(a[0][0]);
//获得数组的首地址
int *p=a[0];
for(i=0;i<len;i++)
printf("==>%d\n",*(p++));
return 0;
}
3 预处理和宏定义
#include 包含一个源代码文件
#define 定义宏
#undef 取消已定义的宏
#if 如果给定条件为真,则编译下面代码
#ifdef 如果宏已经定义,则编译下面代码
#ifndef 如果宏没有定义,则编译下面代码
#elif 如果前面的#if给定条件不为真,当前条件为真,则编译下面代码
#endif 结束一个#if……#else条件编译块
#表示直接替换
#define stringer( x ) printf(#x "\n")
stringer( "In quotes when printed to the screen" );
输出:"In quotes when printed to the screen"
##表示连接符#define VAR(num) v##num
VAR(0)会扩展为v0
#define 宏定义 如果定义变量 优先用typedef
4 结构体中的字节对齐
struct my_struct {
char a;
double b;
}ms;
如果打印sizeof(ms) 在window中为16 在linux中应该是12
5 内存分配
malloc 分配制定大小的内存 返回void * 类型的指针 内存大小单位字节
free 释放内存
calloc 与malloc功能类似 但是他会把分配的内存初始化为0
realloc 修改已分配的内存大小
主要问题应该就是内存泄露了
6 枚举、共用体、位段
7、 回调函数
//t.h
#ifndef TEST
#define TEST
//定义一个函数指针
typedef void (*A)();
//用于函数指针传参
void setCB(A cb);
void start();
#endif
//t.cpp
#include "t.h"
#include <thread>
//定义函数指针变量 用于存储
A c;
void setCB(A cb) {
c = cb;
}
void f1() {
for(;;) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
printf("==>111\n");
//执行回调函数
c();
}
}
void start() {
std::thread t2(f1);
t2.join();
}
//main.cpp
#include <stdio.h>
#include "t.h"
//实现回调函数
void ccc() {
printf("==>cb\n");
}
int main() {
//将函数传参 用于回调
setCB(ccc);
start();
return 0;
}
//ubuntu下编译:
//g++ -std=c++11 -o test ./t.cpp ./main.cpp -lpthread