【发布时间】:2015-03-31 23:36:31
【问题描述】:
我正在从一个文件中读取(每行包含 1 个单词)并将每一行放入一个数组中。但是,每当我尝试访问数组中的任何元素时,都会遇到分段错误。非常感谢您对此的任何帮助。 *更新:添加了一个while循环来逐个抓取字符,但我仍然遇到分段错误
指针是在这里制作的:
char* ptr;
我是这样通过函数的:
fillDict(ptr,&size);
int fillDict(char* ptr,int *size)
它会读取文件并将其放入此处的数组中:
int i = -1;
int numb;
int wsize;
while (fgets(word,30,file)!=NULL)
{
if (i==-1)
{
if(word[strlen(word)-1]=='\n')
{
word[strlen(word)-1] = 0;
}
numb = atoi(word);
ptr = malloc(sizeof(char));
}
else
{
if(word[strlen(word)-1]=='\n')
{
word[strlen(word)-1] = 0;
}
wsize = wsize+strlen(word);
ptr = realloc(ptr,wsize);
int j = 0; //added from here
while(j<strlen(word)-1)
{
printf("%d\n",j);
ptr[j] = word[j]; //crashes here
j++;
}
ptr[j] = '\0'; //to here
size++;
}
i++;
}
printf("%s",ptr[0]); //but fails here
fclose(file);
【问题讨论】:
-
ptr[i] = word;您正在创建一维数组并试图将其视为二维。 -
是的,而且看起来
word指向的内存可能不再有效,因为它超出了while循环的范围。
标签: c arrays malloc pass-by-reference