开发者

Using Pointer to Functions Inside Structs in C

Just for s & g. I wanted to build my own library in C. I wanted to make it follow the C# object notion and realized that the only way to do so is to have the base types use pointers to functions as their members.

Well, I am stuck and have no clue why. The following is a sample of what a String base type may look like:

#ifndef STRING_H
#define STRING_H

typedef struct _string
{
    char* Value;
    int Length;
    String* (*Trim)(String*, char);

} String;

String* String_Allocate(char* s);
String* Trim(String* s, char trimCharacter);

#endif  /* STRING_H */

And the implementation:

String* Trim(String* s, char trimCharacter)
{
    int i=0;
    for(i=0; i<s->Length; i++)
    {
        if( s->Value[i] == trimCharacter )
        {
            char* newValue = (char *)malloc(sizeof(char) * (s->Length - 1));
            int j=1;

            for(j=1; j<s->Length; j++)
            {
                newValue[j] = s->Value[j];
            }

            s->Value = newValue;
        }
        else
        {
            break;
        }
    }

    s->Length = strlen(s->Valu开发者_运维问答e);
    return s;
}

String* String_Allocate(char* s)
{
    String* newString = (String *)malloc(sizeof(String));
    newString->Value = malloc(strlen(s) + 1);
    newString->Length = strlen(s) + 1;
    strcpy(newString->Value, s);

    newString->Trim = Trim;
}

However when compiling this in NetBeans (for c, C++) I get the following error:

In file included from String.c:6:
String.h:8: error: expected specifier-qualifier-list before ‘String’
String.c: In function ‘String_Allocate’:
String.c:43: error: ‘String’ has no member named ‘Trim’
make[2]: *** [build/Debug/GNU-Linux-x86/String.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 77ms)

Can anyone help me understand how come the String->Trim member is non-existent and/or how to fix this?

Thank you


With a recursive structure you need to write

typedef struct _string String;

before you define the struct, or else internally where you have String replace it by struct _string (just until the typedef comes into scope).


Break it to a separate typedef and a field declaration and see if that helps.


The object is nonexistent because the code defining it in the .h file had a syntax error and therefore that error spawned additional errors. Compile and run is so cheap these days that you might as well just fix only the first error, and recompile. As you gain experience you will recognize which errors are the result of earlier ones.

You may want to do a bot of research on object-oriented programming in C because some people have been doing it since before C++ existed. http://www.planetpdf.com/codecuts/pdfs/ooc.pdf

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜