[英]I am getting a segmentation fault core dumped when using strtok
我正在尝试从 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)
我的直觉是我没有正确访问数组中的字符串,导致崩溃,但我不确定。 谢谢你。
我是 C 的菜鸟正在显示。 我忘了放
#include <string.h>
在我的文件中。 这解决了我无法从 pTokens 读取的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.