C函数指针

基本的函数指针:

void (*p)(void *arg);

说明:

void 啥也不返回
(*p)一个函数指针,名字是p
(void *arg)该函数指针所指向的函数的参数应该是void *arg

返回任意值的函数指针

void* (*p)(void *arg);

说明:

void* 返回一个任意类型的对象的地址
(*p)说明这是一个函数指针,名字是p
(void *arg)说明函数指针指向的函数的参数是 void *arg
#include <iostream>
#include <vector>
#include <chrono>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>

void f(char *s)
{
    printf("%s\n", s);
}

char *f2(char *name)
{
    char *t = (char*)malloc(strlen(name)+7);
    memset(t, 0, strlen(name)+7);
    memcpy(t, name, strlen(name));
    memcpy(t+ strlen(name), " hello", 6);
    return t;
}

int main()
{

    void (*p)(void *arg) = (void (*)(void *))f;

    p((void*)"hello");
    void *(*p2)(void *arg) = (void *(*)(void *))f;
    p2((void*)"asdajios90");

    p2 = (void *(*)(void *))f2;

    char *t2 = (char*)p2((void*)"asdasd");
    printf("%s\n", t2);
    free(t2);
    return 0;
}
hello
asdajios90
asdasd hello
文章目录