函数指针作为 C 结构的成员 [英] Function pointer as a member of a C struct

查看:38
本文介绍了函数指针作为 C 结构的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下结构,带有一个指向名为length"的函数的指针,该函数将返回 chars 成员的长度.

I have a struct as follows, with a pointer to a function called "length" that will return the length of the chars member.

typedef struct pstring_t {
    char * chars;
    int (* length)();
} PString;

我有一个函数可以返回从指针到 PString 的字符长度:

I have a function to return the length of the characters from a pointer to a PString:

int length(PString * self) {
    return strlen(self->chars);
}

我有一个函数 initializeString() 返回一个指向 PString 的指针:

I have a function initializeString() that returns a pointer to a PString:

PString * initializeString() {
    PString *str;
    str->length = &length;
    return str;
}

很明显,我在这里的指针做错了,因为 str->length = &length 行在我的调试器中导致 EXC_BAD_ACCESS 信号,`return strlen 也是如此(自我->字符).有没有人对这个问题有任何见解?

It is clear that I am doing something very wrong with my pointers here, because the str->length = &length line causes an EXC_BAD_ACCESS signal in my debugger, as does `return strlen(self->chars). Does anyone have any insights into this problem?

我特别希望能够让 initializeString() 函数返回一个指向 PString 的指针,以及使用指向 PString 的指针作为输入的 length 函数.这只是在 C 中实现基本面向对象系统的一个实验,但我没有很多正面处理指针的经验.感谢您为我提供的任何帮助.

I specifically want to be able have the initializeString() function return a pointer to a PString, and the length function to use a pointer to a PString as input. This is just an experiment in implementing a rudimentary object-oriented system in C, but I don't have a lot of experience dealing with pointers head-on. Thanks for any help you can give me.

推荐答案

分配内存以保存字符.

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

typedef struct PString {
        char *chars;
        int (*length)(PString *self);
} PString;

int length(PString *self) {
    return strlen(self->chars);
}

PString *initializeString(int n) {
    PString *str = malloc(sizeof(PString));

    str->chars = malloc(sizeof(char) * n);
    str->length = length;

    str->chars[0] = ''; //add a null terminator in case the string is used before any other initialization.

    return str;
}

int main() {
    PString *p = initializeString(30);
    strcpy(p->chars, "Hello");
    printf("
%d", p->length(p));
    return 0;
}

这篇关于函数指针作为 C 结构的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆