【发布时间】:2016-01-24 06:36:34
【问题描述】:
我正在尝试在 C 中创建一个函数,该函数读取第一行表单文件并将每个单词存储到字符串数组中,然后返回数组或打印它(我使用了 strtok())。我已经编写了我的代码,但是当我测试它时,我收到一个错误:“分段错误”,我不知道它是什么意思。 有什么帮助吗???我看到了这个问题Segmentation fault with array of strings C 我认为它是相似的,但我还是不明白。 这是我的代码:
从文件中读取数据并将其存储到数组中的函数 函数在文件中:methodes.c
void lireFichier (char *file)
{
int i = 0;
int nbElement = 4;
char ** tab;
char line [1000];
char *str[1000];
const char s[2] = " ";
char *token;
FILE *myFile;
myFile = fopen(file, "r");
if(!myFile)
{
printf("could not open file");
} else
{
printf("file opened\n");
//while(fgets(line,sizeof line,myFile)!= NULL)
//get the fisrt line
fgets(line,sizeof line,myFile);
//fprintf(stdout,"%s",line);
//get the fisrt word
token = strtok(line, s);
for(i =0; (i< nbElement) && (token != NULL); i++)
{
int len = strlen(token);
tab[i] = malloc(len);
strncpy(tab[i], token, len-1);
token = strtok(NULL, s);
//printf( "%s\n", tab[i]);
}
}
fclose(myFile);
}
这是 main.c // 我将文件作为参数传递(在 argv 中)
#include <stdio.h>
#include <stdlib.h>
#include "methodes.h"
int main(int argc, char *argv[])
{
int result = 1;
if(argc < 2)
{
printf("Erreur dans les arguments\n");
} else
{
int idx;
for (idx = 0; idx < argc; idx++)
{
printf("parameter %d value is %s\n", idx, argv[idx]);
}
lireFichier(argv[1]);
}
return 0;
}
这是文件的一个示例:methodes.txt
afficher tableau
partager elements roles
nommer type profession
fin
这是我的输出:
file opened
Erreur de segmentation
注意:输出是法语,所以消息表示分段错误 谢谢你,很抱歉所有的细节,我只是想确保人们理解我的意思。
【问题讨论】:
-
tab未初始化(未分配内存)并使用了tab[i],因此出现分段错误。 -
还有
tab[i] = malloc(len);strncpy(tab[i], token, len-1);token = strtok(NULL, s);-->tab[i] = malloc(len+1); strcpy(tab[i], token);token = strtok(NULL, " \n"); -
@BLUEPIXY 我像这样更改了数组的初始化:char *tab[4],并且代码工作正常。但是当我尝试你在第二条评论中所说的内容时,它给了我一个编译错误:函数的参数太少 \u2018strncpy\u2019 strncpy(tab[i], token);
-
你有错字
strncpyasstrcpy -
@BLUEPIXY 是的,对不起。如果我可以问你另一个问题...我希望我的函数返回一个字符串数组,然后在 main 中使用它;我这样做了: char ** lireFichier(char *line) {....} 主要是: char *tab[4]; tab = lireFichier(line); (我更改了参数,将字符串而不是文件传递给函数)但这不起作用..