Search code examples
carraysmallocstringbuffer

Understanding the StrBuff In C


I need to know if this StrBuff struct is supposed to operate like an array. I've looked and looked, and honestly can't tell just due to the pointer syntax - it seems like as an array it could work, and as an array it could not work.

I see that in the second method, malloc() is used, so I'm guessing that the buf-str uChar is supposed to be an array.

Teh codez:

typedef struct {
    unsigned char *str;
    unsigned int len;
} StrBuf;


static StrBuf *
strbuf_new ()
{
    StrBuf *buf;

    buf = (StrBuf *) calloc (sizeof (StrBuf), 1);
    buf->str = (unsigned char *) strdup ("");
    return buf;
}


static void
strbuf_append (StrBuf *buf, unsigned char *data, int len)
{
    int offset;

    if (len <= -1)
        len = strlen ((char *) data);
    offset = buf->len;
    buf->len += len;
    buf->str = (unsigned char *) realloc (buf->str, buf->len + 1);
    memcpy (buf->str + offset, data, len);
    buf->str[buf->len] = '\0';
}

So, judging from these methods I'm guessing for any C/C++ veterans out there this should be a piece of cake.

Edit:

My goal has been to convert an app (which uses this code here) into a Java port, but I've been quite confused as to how I should do it. I've gotten fairly far doing (for the most part) the same thing in Java, only this time using a byte[] array, seeing as how unsigned chars are supposed to be equivalent to bytes in Java.


Solution

  • It's not an array. It's a structure to hold values (probably strings) using dymamic memory allocation. If you use an array to allocate some datas, then array size is determined at compile time. For example:

    char buf[10];
    

    With a structure like StrBuf you can allocate the required memory when the string buf of the given length is supplied :

    buf->str = (unsigned char *) realloc (buf->str, buf->len + 1);