Smarter strings in C

In C, strings are usually stored in variables with char* type, it's just container for characters, there isn't stored other data/metadata. This can be tedious, e.g. if we want to iterate thought string we need to obtain its length (e.g by invoke strlen() function on it) or carry its length in some additional variables.

This can be simplified by wrapping raw char* string in a simple structure. Its string's length has unsigned type, therefore mistakes with assigning negative values will be easier to find. Its first argument is its content (with char* type), so it can be just passed to functions, that requires regular char* arguments (although it will create warning, it's safe IMHO).

Here is implementation:
#include <stdio.h>
#include <string.h>

typedef struct string {
    char* data;
    unsigned length;
} string;

int main() {
    string myHome; = "it's big and white";
    myHome.length = strlen(;

    // now we don't have to check for size of string,
    // e.g. we don't have to use strlen() to iterate thought charcters
    int i;
    for (i = 0; i < myHome.length; i++) {

    // backward compatibility with char*
    printf("%s\n", myHome); // this will raise warning but is legal

It's a bit unpopular trick, but may be seen in snippets on some forums, also here is tutorial about similar implementation of such strings.

0 commentaires:

Post a Comment