0
Follow
2
View

Saving a string inside a struct in C

dgj123488 注册会员
2023-01-26 10:41

There are two ways to store a string in a struct:

Provide a fixed-length space

struct myType
{
    int imInteger;
    float imFloat;
    char imChar;
    char imString[33];  // strings may not be more than 32 characters long
};

Strings must be copied to the struct:

struct myType mple = {0};

strncpy( example.imString, "Hello world", sizeof(example.imString) );
example.imString[sizeof(example.imString)-1] = '\0';  // make sure it is null-terminated

Use dynamically-allocated strings

struct myType
{
    int imInteger;
    float imFloat;
    char imChar;
    char * imString;  // strings may be any size, but must be managed
};

This is where strdup() is useful:

struct myType example = {0};

example.imString = strdup( "Hello world" );

You must be careful to free() it every time you touch it, though:

free( example.imString );
example.imString = strdup( "Goodbye world" );

free( example.imString );
// destroy example

Initialization matters

Notice that both times I explicitly initialized the struct to zeros? This is a good thing: for the first example you get an empty fixed-length string; for the second example you get a NULL pointer — both of which are good because they provide a consistent, observable state at all times (and let that free() work without error).

Life is easy if you create a constructor:

struct myType create_myType()
{
    ...
}

or:

struct myType * create_myType()
{
    ...
}

void free_myType( struct myType * x )
{
    free( x->imString );
    free( x );
}

Every time you create one, use the explicit constructor:

struct myType example = create_myType();

or:

struct myType * example = create_myType();

...

free_myType( example );

You can even specialize constructors for different types:

struct myType * create_int_myType( int x );
struct myType * create_float_myType( float x );

struct myType * create_string_myType( const char * s )
{
    struct myType * result = create_myType();
    result->imString = strdup( s );
    return result;
}

And so on.

About the Author

Question Info

Publish Time
2023-01-26 10:41
Update Time
2023-01-26 10:41