我正在尝试创建缓冲区来存储符号的无限大小。
我有这个结构:
typedef struct buffer {
int bufferSize;
int literalSize;
int allocatedSize;
char *bufferPtr;
} bufferStruct;
在我的 file.h 。
中我还有缓冲区函数:
bufferStruct *BufferInitialize(int size) {
bufferStruct *tempBuff;
tempBuff = (bufferStruct *)malloc(sizeof(bufferStruct));
if (tempBuff == NULL) {
exit(99); // MEMORY_ERROR
}
tempBuff->bufferSize = size;
tempBuff->literalSize = 0;
tempBuff->bufferPtr = NULL;
tempBuff->allocatedSize = 0;
return (tempBuff);
}
int addToBuffer(bufferStruct *buffer, char c) {
if (buffer == NULL) {
return 99; // MEMORY_ERROR
}
if (buffer->allocatedSize > buffer->literalSize) {
buffer->bufferPtr[buffer->literalSize++] = c;
} else {
buffer->bufferPtr = realloc(buffer->bufferPtr, (buffer->allocatedSize + buffer->bufferSize) * sizeof(char));
if (buffer->bufferPtr == NULL) {
return 99; // MEMORY_ERROR
}
buffer->allocatedSize += buffer->bufferSize;
buffer->bufferSize <<= 1; // bS = bS * 2
buffer->bufferPtr[buffer->literalSize++] = c;
}
return 0;
}
int bufferDestroy(bufferStruct *buffer) {
if (buffer == NULL) {
return 99; // MEMORY_ERROR
}
free(buffer->bufferPtr);
free(buffer);
return 0;
}
在我的 file.c 中,我正在尝试创建缓冲区:
token *getNextToken(token *tokenT) {
token *actualToken = NULL;
char *bufferData = NULL;
int charFromFile;
eState state = stateInit;
bufferStruct *bufferT = NULL;
while ((charFromFile = fgetc(fp))) {
switch (state) {
case stateInit: {
if (isdigit(charFromFile)) {
bufferT = BufferInitialize(8);
addToBuffer(bufferT, charFromFile);
state = stateInt;
} else
if (isalpha(charFromFile) || (charFromFile == '_')) {
state = stateId;
bufferT = BufferInitialize(16);
addToBuffer(bufferT, charFromFile);
} else
if (isspace(charFromFile)) {
state = stateInit;
... some more conditions ... it's similar, a lot.
case stateInt: {
if (isdigit(charFromFile)) {
state = stateInt;
addToBuffer(bufferT, charFromFile);
} else
if ((charFromFile == 'e') || (charFromFile == 'E')) {
state = stateExp;
addToBuffer(bufferT, charFromFile);
} else
if (charFromFile = '.') {
state = stateDouble;
addToBuffer(bufferT, charFromFile);
} else {
bufferData = bufferT->bufferPtr;
//strcpy(actualToken->content, bufferData);
addToBuffer(bufferT, '\0');
bufferDestroy(bufferT);
actualToken->type = tokenInt;
return actualToken;
}
} break;
... other similar cases ...
}
}
}
问题是当我试图这样做时,Visual studio会给我错误:
One or more multiply defined symbols found
也给了我already defined in main.obj
对于我的每一项功能。
我没有看到出路。我究竟做错了什么 ?
答案 0 :(得分:1)
您的代码中存在多个问题:
您不应将代码放在头文件中。函数BufferInitialize
不应位于file.h
,除非已定义inline
。
测试while (c = fgetc(fp))
不正确:您使用赋值作为测试表达式,它非常容易出错,您至少应该为赋值表达式括号,并且可能会测试EOF
而不是'\0'
:while ((c = fgetc(fp)) != EOF)
。此外,c
必须定义为int
。发布实际代码,而不是伪代码。
您将tempBuff->bufferSize
初始化为可能非零值,而allocatedSize
为0
且缓冲区未分配。这似乎不正确。
您的实际代码中可能存在更多问题,我们无法看到代码是什么,如何告诉您这些代码?始终发布一个完整的,可编译的代码来证明问题。