理解 C 语言中的 StrBuff
我需要知道这个 StrBuff 结构是否应该像数组一样操作。我看了又看,老实说,仅仅因为指针语法就无法判断 - 看起来作为一个数组它可以工作,而作为一个数组它不能工作。
我看到在第二种方法中使用了 malloc() ,所以我猜测 buf-str uChar 应该是一个数组。
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';
}
所以,从这些方法来看,我猜对于任何 C/C++ 老手来说,这应该是小菜一碟。
编辑:
我的目标是将应用程序(此处使用此代码)转换为 Java 端口,但我对于应该如何执行它感到非常困惑。我已经在 Java 中做了相当多的事情(大部分),只是这次使用了 byte[] 数组,看看无符号字符应该与 Java 中的字节等效。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不是一个数组。它是一个使用动态内存分配来保存值(可能是字符串)的结构。如果使用数组来分配一些数据,则数组大小在编译时确定。
例如:
使用 StrBuf 这样的结构,您可以在提供给定长度的字符串 buf 时分配所需的内存:
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:
With a structure like StrBuf you can allocate the required memory when the string buf of the given length is supplied :