我在使用strtok时收到了一个分段故障核心

问题描述 投票:-1回答:1

我试图从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 csv parsing segmentation-fault
1个回答
0
投票

我是C的菜鸟。我忘记了

#include <string.h> 

在我的档案中。这解决了我无法从pTokens读取的问题。

© www.soinside.com 2019 - 2024. All rights reserved.