我在另一个函数中将内存分配给双指针,因此我需要使用指向指针的指针。我在使用 sscanf 时抛出异常,我不确定到底是为什么。这是代码片段。当它们都在同一个函数中并且我只需要使用双指针时,它在早些时候工作,但现在我重构代码并使用三指针我遇到了这个问题。
typedef float vector[3]
int mainLoaderFunc() {
char* memory = NULL;
size_t size = loadFile(fileName, &memory); // load model file into memory, this works, tested and true
// create vector arrays
vector *vertexArray = NULL;
vector *normalArray = NULL;
vector *textureArray = NULL;
loadArrays(size, memory, &vertexArray, &normalArray, &textureArray);
// do other stuff with arrays
}
void loadArrays(size_t size, char *memory, vector **vertexArray, vector **normalArray, vector **textureArray) {
int numVerts = 0;
int numNormals = 0;
int numTextures = 0;
char* p = memory; // pointer to start of memory
char* e = memory + size; // pointer to end of memory
// count verts, normals, textures for memory allocation
while (p != e) {
if (memcmp(p, "vn", 2) == 0) {
numNormals++;
} else if (memcmp(p, "vt", 2) == 0) {
numTextures++;
} else if (memcmp(p, "v", 1) == 0) {
numVerts++;
}
while (*p++ != (char) 0x0A);
}
// allocate memory for vector arrays
*vertexArray = new vector[numVerts];
*normalArray = new vector[numNormals];
*textureArray = new vector[numTextures];
p = memory;
int vertexIndex = 0;
int normalIndex = 0;
int textureIndex = 0; //*** IF BREAK POINT HERE: NO EXCEPTION
// load data from memory into arrays
while (p != e) {
if (memcmp(p, "vn", 2) == 0) {
sscanf(p, "vn %f %f %f", &normalArray[normalIndex][0], &normalArray[normalIndex][1], &normalArray[normalIndex][2]);
normalIndex++;
} else if (memcmp(p, "vt", 2) == 0) {
sscanf(p, "vt %f %f", &textureArray[textureIndex][0], &textureArray[textureIndex][1]);
textureIndex++;
} else if (memcmp(p, "v", 1) == 0) {
sscanf(p, "v %f %f %f", &vertexArray[vertexIndex][0], &vertexArray[vertexIndex][1], &vertexArray[vertexIndex][2]);
vertexIndex++;
}
while (*p++ != (char) 0x0A);
}
}
一旦代码命中 sscanf 部分,我就会得到异常:
Unhandled exception at 0x5e9cf2dc (msvcr100d.dll) in derp.exe: 0xC0000005: Access violation writing location 0xcccccccc.
最佳答案
您将无效地址传递给 sscanf
。查看函数的一个参数:
vector **vertexArray
vertexArray
指向从 mainLoaderFunc
传递过来的指针的地址。 *vertexArray
指的是指向实际 vector
数组的指针,正如您在为其分配内存时所意识到的那样:
*vertexArray = new vector[numVerts];
因此数组中的有效元素为:
(*vertexArray)[vertexIndex][0]
注意您的代码缺少的*
; *vertexArray
指的是实际数组。现在 sscanf
想要这个变量的地址,所以现在获取它的地址(为清楚起见添加了额外的括号):
&( (*vertexArray)[vertexIndex][0] )
将你所有的 sscanf
参数都改成这样。
关于c++ - 传递三重指针以在另一个函数中分配内存,sscanf 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8596563/