数组指针操作的常用几种方式
void main(){
int arr[] = {1,2,3,4,5,6};
int i = 0;
for (; i < 6;i++){
//第一种
printf("位置%d的值是:%d\n", i, *(arr + i));
//第二种
printf("位置%d的值是:%d\n", i, arr[i]);
}
getchar();
}
内存开辟
- 静态开辟
/*
静态开辟内存,方法结束后会自动回收
*/
void staticMalloc(){
int arr[6];
int i = 0;
for (; i < 6;i++){
arr[i] = i;
printf("%d %p\n", *(arr + i), arr + i);
}
}
*动态内存开辟和释放
/*
动态开辟内存 方法结束不会自动回收
*/
void dynaMalloc(){
//malloc申请需要的内存返回void* 这里强转成你需要的指针类型
int * arr=(int *) malloc(sizeof(int)*10*1024*1024);
//手动释放内存
if (arr !=NULL){
free(arr);
}
}
函数指针(常用于回调)
void add(int a,int b){
printf("a+b=%d\n", a + b);
}
void mins(int a,int b ){
printf("a-b=%d\n", a - b);
}
//方法的返回类型(*方法的名称)(方法的参数)
void opeate(void (*method)(int,int),int a,int b){
method(a,b);
}
void main(){
//正常调用
add(1,2);
//指针调用
//定义:方法的返回类型(*方法的名称)(方法的参数)
void(*add_p)(int, int) = add;
add_p(1,2);
opeate(add, 1, 2);
opeate(mins, 1, 2);
getchar();
}
结构体、结构体指针别名
struct Worker
{
int age;
char name[10];
};
//对结构体指定别名
typedef Worker Person;
void test1(){
Person person = {23,"张三"};
printf("name = %s ,age = %d \n ", person.name, person.age);//name = 张三 ,age = 25
}
//对结构体指针指定别名
typedef Worker * Worker_P;
void test2(){
Worker_P worker_p = (Worker *)malloc(sizeof(Worker));
worker_p->age = 25;
printf("age = %d \n ", worker_p->age);//age = 25
}
- 结构体指针使用的方式
struct Worker
{
char name[10];
int age;
};
//第一种方式
void test1()
{
struct Worker worker = { "张三",56 };
Worker* worker_p = &worker;
//结构体一般用worker.name ="" 指针一般用worker_p->name =""
worker_p->age = 24;
strcpy(worker_p->name, "李四");
printf("name = %s,age= %d \n", worker_p->name, worker_p->age);//name = 李四,age= 24
}
//第二种方式 比较常用
void test2() {
Worker *worker_p =(Worker*) malloc(sizeof(Worker));
strcpy(worker_p->name, "李四");
worker_p->age = 24;
printf("name = %s,age= %d \n", worker_p->name, worker_p->age);//name = 李四,age= 24
//释放
if (worker_p) {
free(worker_p);
worker_p = NULL;
}
}