天天看点

C语言-指针数组月数组指针,结构体数组,结构体指针,结构体指针数组

指针数组

指针数组是一个数组,数组的元素保存的是指针;

定义:

int *p[size] //表示数组存的是指针,有size个指针数据

数组指针

数组指针是一个指针,该指针指向的是一个数组;

定义:

int (*p)[size] //数组指针,存储size个int类型的数据

指针函数与函数指针

指针函数

指针函数是一个函数,该函数返回的是一个指针;

函数指针

函数指针是一个指针,该指针指向一个函数;

#include <stdio.h>
 
int* getIntPoint(const int a) //指针函数,是一个函数 返回一个指针;
{
	int *p = nullptr ;
	p = new int ;
	*p = a; 
 	return p ;
}
 
 
int main(int argc, char const *argv[])
{
	int *(*p)(int)  = getIntPoint ; //函数指针,该指针指向一个函数;
	int* pInt = p(5); //使用函数指针;
	printf("%d\n",*pInt);
	delete pInt ;
	return 0;
}
           
#include <stdio.h>
void print();
int main(void)
{
	void (*fuc)(); 
	fuc = print ; 
	fuc(); 	
} 
void print()
{
	printf("hello world!\n");
}
           

回调函数

函数指针变量可以作为某个函数的参数来使用的,回调函数就是一个通过函数指针调用的函数。

#include <stdlib.h>  
#include <stdio.h>
 
// 回调函数
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue();
}
 
// 获取随机值
int getNextRandomValue(void)
{
    return rand();
}
 
int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    for(int i = 0; i < 10; i++) {
        printf("%d ", myarray[i]);
    }
    printf("\n");
    return 0;
}
           

结构体数组

数组中存储的元素都是一个结构体,类似整型数组中存储的是int型。

申明结构体数组:

结构体名 数组名【size】

结构体指针

指向结构体的指针。

结构指针变量说明的一般形式为:

struct 结构体名 *结构体指针变量名

struct student *p = &Boy; //假设事先定义了 struct student Boy;

#include<stdio.h>
#include<string.h>
#include<malloc.h>

typedef struct Errlog
{
	char str_file[1000];
	int num;
	int err;
}errlog;

int main(void)
{
	errlog err1[3];//结构体数组
	errlog *err2;//结构体指针
	errlog *err3[3];//结构体指针数组,表示数组存的是指针,有3个指针数据
	errlog (*err4)[3];//结构体数组指针,是一个指针,该指针指向的是一个数组,该数组存储3个errlog类型的数据

}

           

理解:结构体数组指针就是一个指针,感觉没有实际意义,可用普通指针代替。

继续阅读