我正在尝试从csv文件中读取数字,然后将这些数字传递给我称为pTokens的char * []。一切似乎工作正常,因为char * []被填充,但当我尝试从数组访问一个元素时,我得到一个分段错误。 (当我尝试手动输入文件名时,它似乎也会崩溃,因此它被注释掉了。但这又是另一个问题。)
FILE *infile = NULL;
char line[1024] = "", copyLine[1024] = "";
char *pTokens[1024] = { NULL };
int index = 0;
int i;
int j = 0;
.
.
.
case 8:
printf("Enter the file name (test.csv):\n");
//scanf("%s", name);
infile = fopen("values.csv", "r");
if(infile != NULL){
printf("successfully opened\n");
fgets(line, 100, infile);
strcpy(copyLine, line);
pTokens[index] = strtok(copyLine, ",");
puts(line);
while (pTokens[index] != NULL)
{
++index;
pTokens[index] = strtok(NULL, ","); // token
}
while(pTokens[j] != NULL){
puts(pTokens[j]);
j++;
}
}else{
printf("Failed to open file.\n");
cond = 0;
}
我的输出如下:
1. Create a new node
2. Delete a node
3. Print the Pre-Order of the tree
4. Print the In-Order of the tree.
5. Find min of the tree
6, Find max of the tree.
8. Create Tree from CSV.
9. Exit.
8
Enter the file name (test.csv):
successfully opened
50,30,20,40,70,60,80
Segmentation fault (core dumped)
我的直觉是,我没有正确访问数组中的字符串,导致崩溃,但我不确定。谢谢。
答案 0 :(得分:0)
我是C的菜鸟。 我忘了把
#include <string.h>
在我的档案中。这解决了我无法从pTokens读取的问题。