Page 1 of 1

typedef struct + assignments

Posted: Sat Feb 28, 2009 5:59 pm
by Troy Martin
Hey all,

I was wondering if anyone knew how to do something like this:

Code: Select all

typedef struct
{
    int length = strlen(this); /* get the length of the string pointed to by the variable declared here */
} *string_sz;

string_sz str = "Hello World!\n";
So str is a pointer to a C string and length is the string's length.

Will that work or do I have some modifications to make to get it to work like a string from the C++ string library?

Re: typedef struct + assignments

Posted: Sat Feb 28, 2009 6:09 pm
by JohnnyTheDon
No, it won't work :( . You need a bunch of functions in a class to do this kind of thing.

Code: Select all

class sz_string
{
public:
    String(const char* str="") { mString = str; mLength = strlen(str); }
    operator const char*() const { return mString; }
    int Length() const { return mLength; }
protected:
    const char* mString;
    int mLength;
}
If you're trying to do this in C, AFAIK it isn't possible.

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 5:02 am
by Creature
What JohnnyTheDon says. You can pretty much not do that in C, because C doesn't support (as far as I know) nor operator overloading, nor functions in structures.

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 5:07 am
by 01000101
AFAIK you're stuck with using plain ol' char arrays and using strlen(x). =)

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 10:50 am
by Troy Martin
Yuck, this sucks.

Oh well, thanks anyways!

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 5:08 pm
by JamesM
Think about it - if you change the value of the char* member, how would the length member update? C has no runtime support system.

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 6:43 pm
by Love4Boobies
JamesM made the same point I wanted to make but here's another - WHY would this ever be needed?

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 7:03 pm
by JohnnyTheDon
Getting the length of a string with running strlen every time.

Re: typedef struct + assignments

Posted: Sun Mar 01, 2009 7:09 pm
by Love4Boobies
Well it's not stored anywhere. If you want this to happen, just make sure you update a variable with the length of the string each time you change it.

EDIT: Or you Pascal :)

Re: typedef struct + assignments

Posted: Mon Mar 02, 2009 5:40 am
by Combuster
or link to the freebasic runtime (written in C :) ) and use that string format + functions

In the end, it all boils down to the same thing...

Re: typedef struct + assignments

Posted: Mon Mar 02, 2009 7:25 am
by Love4Boobies
Combuster wrote:In the end, it all boils down to the same thing...

Boobies?

Sorry, couldn't help it...

Re: typedef struct + assignments

Posted: Mon Mar 02, 2009 9:25 am
by Combuster
Also an option, but it only circumvents the problem by not having to write code :twisted: