我成功编写了将包含文本数据的 .dat 文件写入一维数组的代码。但是,当我尝试开发代码以将这些文件写入二维数组时,我一直陷入指针问题。以下代码是我要修复的:
while (getline(fin, line)) {
char* buf = _strdup(line.c_str());
// parse the line into blank-delimited tokens
int n = 0; // a for-loop index
int s = 0;
int m = 0;
// array to store memory addresses of the tokens in buf
const char* token[MAX_TOKENS_PER_LINE][MAX_TOKENS_PER_LINE] = {};
char *next_token;
// parse the line
token[0][0] = strtok_s(buf, DELIMITER, &next_token); // first token
//token[0] = strtok(buf, DELIMITER); // first token
if (token[0][0]) {
// zero if line is blank
for (n = 1; n < MAX_TOKENS_PER_LINE; n++) {
token[m][n] = strtok_s(0, DELIMITER, &next_token);
//token[n] = strtok(0, DELIMITER);
if (!token[m][n]) break; // no more tokens
m++;
}
}
// process (print) the tokens
for (int i = 0; i < n; i++) // n = #of tokens
for (int j = 0; j<m; j++) {
cout << "Token[" << i << "," << j << "] = " << token[i][j] << endl;
cout << endl;
}
fin.clear();
fin.close();
free(buf);
}
显然,在第一行之后,第一个标记token[0][0]
将指向垃圾,因为不同的数据将在buf
. 如何避免这个问题?