1

我正在读取缓冲区(char *)并且我有一个光标,我在其中跟踪缓冲区的起始位置,有没有办法将字符 7-64 复制出缓冲区,或者我最好的选择只是循环从位置 x 到位置 y 的缓冲区?

目标缓冲区的大小是另一个函数动态计算的结果

初始化这个返回

variable-sized object 'version' may not be initialized

相关代码部分:

int32_t size = this->getObjectSizeForMarker(cursor, length, buffer);
cursor = cursor + 8; //advance cursor past marker and size
char version[size] = this->getObjectForSizeAndCursor(size, cursor, buffer);

-

char* FileReader::getObjectForSizeAndCursor(int32_t size, int cursor, char *buffer) {
  char destination[size];
  memcpy(destination, buffer + cursor, size);
}

-

int32_t FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
  //skip the marker and read next 4 byes
  cursor = cursor + 4; //skip marker and read 4
  unsigned char *ptr = (unsigned char *)buffer + cursor;
  int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
  return objSize;

}
4

1 回答 1

1

将指针buffer向前移动六个单位(以到达第七个索引),然后memcpy移动 64-7 (57) 个字节,例如:

const char *buffer = "foo bar baz...";
char destination[SOME_MAX_LENGTH];
memcpy(destination, buffer + 6, 64-7);

您可能希望终止该destination数组,以便可以使用标准 C 字符串函数来处理它。请注意,我们在第 58个索引处添加了空字符,在被复制的 57 个字节之后:

/* terminate the destination string at the 58th byte, if desired */
destination[64-7] = '\0'; 

如果您需要使用动态大小的destination,请使用指针而不是数组:

const char *buffer = "foo bar baz...";
char *destination = NULL;

/* note we do not multiply by sizeof(char), which is unnecessary */
/* we should cast the result, if we're in C++ */
destination = (char *) malloc(58); 

/* error checking */
if (!destination) { 
    fprintf(stderr, "ERROR: Could not allocate space for destination\n");
    return EXIT_FAILURE;
}

/* copy bytes and terminate */
memcpy(destination, buffer + 6, 57);
*(destination + 57) = '\0';
...

/* don't forget to free malloc'ed variables at the end of your program, to prevent memory leaks */
free(destination); 

老实说,如果您使用 C++,那么您真的应该使用 C++字符串库std::string类。然后,您可以在您的实例上调用substrsubstring 方法string来获取感兴趣的 57 个字符的子字符串。这将涉及更少的头痛和更少的重新发明轮子。

但是上面的代码应该对 C 和 C++ 应用程序都有用。

于 2012-10-07T02:59:48.153 回答