ポインター(2)-ポインターと関数

ポインターの基本(2)-ポインターと関数

ポインタ関数

タイプがポインタである関数のみを返します

#include<stdio.h>

typedef int* Pint;
Pint function();

int main() {
    
    
	Pint p = function();
	printf("%d\n", *p);      // 结果: 0(错误代码,但是VS2019可以正常运行)
	printf("%d\n", *p);      // 结果: 一串无意义的随机数
	//此处function函数中的指针pn只能存活在函数一次调用结束
	//因此这里仅仅验证函数可以返回指针类型
	return 0;
}

Pint function() {
    
    
	int num = 0;
	int* pn = &num;
	return pn;
}

注意:

ポインタ関数を使用すると、スタック領域へのポインタを返すことはできません(ここでのフォローアップ記事はわかりません)

2つの関数ポインタ

関数型へのポインタ

#include<stdio.h>

void fun() {
    
    
	printf("fun is been used!\n");
}

int function(char a, int n) {
    
    
	printf("MuShan!!!\n");
	return 0;
}

int main() {
    
    
	// 返回值类型(*函数指针名)(形参类型)
	int(*Pfunction)(char, int) = function;
	char ch = 0;
	int num = 0;
	Pfunction(ch, num);

	fun();
	//  指针指向的类型* 指针名;
	//  void() ==> void(* )()
	void(*pfun1)() = &fun; // pfun1: &fun ==> *pfun1: fun
	void(*pfun2)() =  fun; // pfun2:  fun
	
	(*pfun1)();
	pfun1();

	(*pfun2)();
	pfun2();
    // 都可正常输出
	return 0;
}

おすすめ

転載: blog.csdn.net/zhuiyizhifengfu/article/details/113836554