在函数之间传递函数指针

时间:2018-08-16 15:37:00

标签: c++ function-pointers

我正在为Generic Stack.SO编写程序,所以我将函数指针传递给函数StackNew() API。当我看到StringFree API的地址时,它是0x012b2770

Memory Window for StackNew

但是当我看到(*免费)API的地址时,它是0x012B13ED

Memory window for free

我以为指针的副本将被传递。如您所见,这没有发生,但是程序正在正常运行。

我认为传递了StringFree API的起始地址,例如假设StringFree的起始地址为0x10,则将0x10传递给免费的API,以便free也指向StringFree的起始地址,以便free也将是0x10,但是那没有发生。您能解释一下这是怎么回事吗?谢谢。

我的程序:

#include<cstdio>  
#include<cstdlib>
#include<cstring>
#include<string.h>
#include<iostream>

using namespace std;

typedef struct
{
    void *elems;
    int loglen;
    int alloclen;
    int elemSize;
    void (*freefn) (void*);
}Stack;

void StringFree(void* target)
{
    char** s = (char**)target;
    free(*s);
    if (s != NULL) {
        std::cout << "Not null" << std::endl;
    }
    s = NULL;

}

void StackNew(Stack *s, int elemSize,void (*free) (void*))
{
    s->elemSize = elemSize;
    s->loglen = 0;
    s->alloclen = 4;
    s->elems = malloc(4 * elemSize);
    s->freefn = free;
    //assert(s->elems != 0 );

}

void StackDispose(Stack *s)
{
    if (s->freefn != 0)
    {
        for (int i = 0 ; i < 3 ; i++ )
        {
            void* source = (char*)s->elems + i*s->elemSize;
            s->freefn(source);
        }
    }

}

void StackPush(Stack *s, void* elemAddr)
{
    if (s->alloclen == s->loglen)
    {
        s->alloclen *= 2;
        s->elems = realloc(s->elems, s->alloclen * s->elemSize);

    }
    void* target = (char*)s->elems + s->loglen*s->elemSize;
    memcpy(target, elemAddr, s->elemSize);
    s->loglen++;

}

void* StackPop(Stack *s, void* elemAddr)
{
    s->loglen--;
    void* source = (char*)s->elems + s->loglen * s->elemSize;
    memcpy(elemAddr, source, s->elemSize);
    return elemAddr;
}


int main()
{

    Stack s;
    std::cout << sizeof(s.freefn) << std::endl;
    const char* friends[] = { "AlexJonesisabitchofjoerogan" , "Bob" , "Carl"};
    StackNew(&s, sizeof(char*),StringFree);
    for (int i = 0; i < 3; i++)
    {
        //int* cc = (int *)_strdup(friends[i]);
        char* copy = _strdup(friends[i]);
        std::cout << copy << std:: endl;
        StackPush(&s, &copy);
    }

    char* name;
    for (int i = 0; i < 3; i++)
    {
        StackPop(&s, &name);
        printf("%s\n", name);
        // free()
    }

    StackDispose(&s);
    std::cin.get();

    return 0;
}

1 个答案:

答案 0 :(得分:1)

指针仍然按值传递,因此当您传递指针时,它会像复制整数一样复制指针的值。