指針數組
指針數組是一個數組,數組的元素保存的是指針;
定義:
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;