Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解C语言中的StrBuff_C_Arrays_Malloc_Stringbuffer - Fatal编程技术网

理解C语言中的StrBuff

理解C语言中的StrBuff,c,arrays,malloc,stringbuffer,C,Arrays,Malloc,Stringbuffer,我需要知道这个StrBuff结构是否应该像数组一样运行。我看了又看,老实说,由于指针语法的原因,我说不出来——它似乎作为一个数组可以工作,作为一个数组它不能工作 我看到在第二个方法中使用了malloc(),所以我猜buf str uChar应该是一个数组 德科兹: typedef struct { unsigned char *str; unsigned int len; } StrBuf; static StrBuf * strbuf_new () { StrBuf

我需要知道这个StrBuff结构是否应该像数组一样运行。我看了又看,老实说,由于指针语法的原因,我说不出来——它似乎作为一个数组可以工作,作为一个数组它不能工作

我看到在第二个方法中使用了malloc(),所以我猜buf str uChar应该是一个数组

德科兹:

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';
}
typedef结构{
无符号字符*str;
无符号整数len;
}StrBuf;
静态StrBuf*
strbuf_新()
{
StrBuf*buf;
buf=(StrBuf*)calloc(sizeof(StrBuf),1);
buf->str=(无符号字符*)strdup(“”);
返回buf;
}
静态空隙
strbuf_append(strbuf*buf,无符号字符*数据,整数长度)
{
整数偏移量;
if(len-len;
buf->len+=len;
buf->str=(无符号字符*)realloc(buf->str,buf->len+1);
memcpy(buf->str+偏移量,数据,len);
buf->str[buf->len]='\0';
}
所以,从这些方法来看,我猜对于任何C/C++老手来说,这应该是小菜一碟

编辑:


我的目标是将一个应用程序(在这里使用此代码)转换为Java端口,但我对该如何做感到非常困惑。我在Java中做了(大部分)同样的事情,只是这次使用了字节[]数组,看看无符号字符在Java中是如何与字节等效的。

它不是数组。它是一种使用动态内存分配来保存值(可能是字符串)的结构。如果使用数组来分配一些数据,则数组大小在编译时确定。 例如:

char buf[10];
使用类似StrBuf的结构,您可以在提供给定长度的字符串buf时分配所需的内存:

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

问题到底是什么?如何像数组一样工作?你想用它做什么?@Overbose那么,如果我要在Java中复制它,我应该创建一个StringBuffer?我一直在将一个使用该代码的应用程序转换为Java端口。我遇到了一些问题,这些问题确实让我怀疑我是否做错了。在java您可以简单地使用字符串。如果您想知道的话,我已经在使用StrBuff了,它的Str数据成员只是一个字节数组。我认为array=new byte[num];,与malloc()一样在c中,取决于存储的数据。StrBuf似乎应该包含字符串。如果是这样,那么在java中只需声明一个新字符串();我想它实际上是在读取文件并存储数据。在这种情况下,您建议我使用字节吗?