对结构的2D变量数组有疑问。
尝试解析文本文件并使用以下函数填充数组:
void populateTable(int x; int y; Entry table[x][y],
int x, int y, char fileName[])
{
char currentLineStr[8192];
int yIndex = 0;
FILE *fileIn;
FILE *fileOut;
fileIn = fopen(fileName, "r");
if(fileIn == 0)
{
perror("Cannot open input file\n");
system("PAUSE");
exit(-1);
}
else
{
fgets(currentLineStr, 8192, fileIn);
while (currentLineStr[0] == '#')
fgets(currentLineStr, 8192, fileIn);
TokenizeLine(currentLineStr, table, yIndex, x, y);
yIndex++;
while(fgets(currentLineStr, 8192, fileIn) != NULL)
{
TokenizeLine(currentLineStr, table, yIndex, x, y);
yIndex++;
//printf("%i\n",yIndex);
}
fclose(fileIn);
}
printf("%s\n", table[0][0].str);
printf("%f\n", table[1][0].dVal);
}
此末尾的printf
语句返回它们应该的值。但是,在调用此函数后,我立即执行相同的printf
语句,并返回错误的信息。
int main(int argc, char *argv[])
{
char stringToFind[256] = {"DWL_FaceMountTile"};
char fileName[64] = {"rtest.txt"};
char timeFile[64] = {"timefile.msgr"};
int numEntries = 0;
int x;
int y;
double time;
double temp;
int tTableXdim = 36;
int tTableYdim = 20;
x = NumColumns(fileName);
y = NumRows(fileName);
Entry eTable[x][y];
Entry tTable[x][y];
int idInstances[y];
int rowQuantity[y];
double clipLines[x][y];
populateTable(tTable,tTableXdim,tTableYdim,timeFile);// call for above code.
printf("%s\n", tTable[0][0].str);
printf("%f\n", tTable[1][0].dVal);// I call these any they return wrong
如果有人能够对这个问题有所启发,我会非常感激。
编辑(建议我发布我的TokenizeLine
功能):
void TokenizeLine(int x; int y; char currentLineStr[], Entry table[x][y], int yIndex, int x, int y)
{
char *tokPtr;
char *current;
int xIndex = 0;
current = currentLineStr;
tokPtr = mystrsep(¤t, "|");
while(tokPtr != NULL)
{
if(IsDouble(tokPtr))
{
table[xIndex][yIndex].str = NULL;
table[xIndex][yIndex].dVal = atof(tokPtr);
}
else
{
table[xIndex][yIndex].str = malloc(strlen(tokPtr) + 1);
strcpy(table[xIndex][yIndex].str, tokPtr);
table[xIndex][yIndex].dVal = 0;
}
tokPtr = mystrsep(¤t, "|")
xIndex++;
}
}
根据要求Entry
定义。
typedef struct Entry
{
char *str;
double dVal;
} Entry;
我在populateTable
函数中得到的输出是。
DWL_FaceMountTile
1.000000
这是完全正确的,并且在populateTable
以下是我在调用populateTable
之后访问表格时获得的内容。
表的str值似乎都是正确的,但dVal都以某种方式设置为零,如下所示。
DWL_FacMountTile
0.000000