Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 从文本文件复制文件时,C-数组不起作用_Arrays_C_File - Fatal编程技术网

Arrays 从文本文件复制文件时,C-数组不起作用

Arrays 从文本文件复制文件时,C-数组不起作用,arrays,c,file,Arrays,C,File,出于某种原因,当我将单词从文件复制到数组时,最后一个元素将替换以前索引中的所有内容;但是,在通过“文件循环”之前,我通过向索引0和1添加文本测试了数组是否工作正常。请看一看: FILE *file = fopen("words.txt", "r"); if (file == NULL){ printf("...\n"); return false; } char *words[172805]; //Array t

出于某种原因,当我将单词从文件复制到数组时,最后一个元素将替换以前索引中的所有内容;但是,在通过“文件循环”之前,我通过向索引0和1添加文本测试了数组是否工作正常。请看一看:

FILE *file = fopen("words.txt", "r");
 if (file == NULL){
    printf("...\n");
    return false;
 }

char *words[172805];

//Array test
words[0] = "abc";
words[1] = "bcde";
printf("%s, %s\n", words[0], words[1]);

// Copy words in text document to 'words' array.
while (!feof(file)) {
    if (fgets(arraywordindic, 15, file) != NULL) {
        //Remove \n from word in arraywordindic
        arraywordindic[strcspn(arraywordindic, "\n")] = '\0';
        words[i] = arraywordindic;
        printf("%s\n", words[i]);
        i++;
        if (i == 4) {break;}
    }
}

for (i = 0; i < 4; i++) {
    printf("%s, ", words[i]);
}

fclose(file);
FILE*FILE=fopen(“words.txt”、“r”);
if(file==NULL){
printf(“…\n”);
返回false;
}
字符*字[172805];
//阵列测试
字[0]=“abc”;
字[1]=“bcde”;
printf(“%s,%s\n”,单词[0],单词[1]);
//将文本文档中的单词复制到“单词”数组。
而(!feof(文件)){
if(fgets(arraywordindic,15,文件)!=NULL){
//从arraywordindic中的word中删除\n
arraywordindic[strcspn(arraywordindic,“\n”)]='\0';
文字[i]=数组格式;
printf(“%s\n”,字[i]);
i++;
如果(i==4){break;}
}
}
对于(i=0;i<4;i++){
printf(“%s”,字[i]);
}
fclose(文件);
上述代码的输出为:

abc bcde

A

AA

哎呀

啊,啊,啊,啊,啊


你知道为什么会这样吗?谢谢。

看起来您正在反复设置指向同一缓冲区的指针。您需要复制字符串,或者换句话说:

words[i] = strdup(arraywordindic);

在C语言中,当你说
char*x=y
时,它不会复制该字符串的内容,它会复制指向该字符串的指针。

看起来你在反复设置指向同一缓冲区的指针。您需要复制字符串,或者换句话说:

words[i] = strdup(arraywordindic);

在C语言中,当你说
char*x=y
时,它不会复制该字符串的内容,而是复制指向该字符串的指针。

为什么
172805
?这是一个非常特殊的数字。我需要存储在数组中的单词数是172806。这是你不想在C中做的假设。如果是这样的话,你也少了一个。最好根据需要使用
realloc
或链表结构动态分配越来越多的内存。谢谢。不是为了这个练习,这就是我们需要的全部字数。对于动态数组,我使用内存分配函数,正如您所提到的。哦,我现在知道了,谢谢。为什么
172805
?这是一个非常特殊的数字。我需要存储在数组中的单词数是172806。这是你不想在C中做的假设。如果是这样的话,你也少了一个。最好根据需要使用
realloc
或链表结构动态分配越来越多的内存。谢谢。不是为了这个练习,这就是我们需要的全部字数。对于动态数组,我使用内存分配函数,正如您所提到的。哦,我现在知道了,谢谢。