c - 我正在尝试将文件中的字符串列表存储到 C 中的数组中
问题描述
我正在尝试读取包含单词列表的文件并将它们存储在数组中。存储后,我随机尝试打印第 10 个元素以确保代码完成了它应该做的事情,但我没有成功。我还收到以下警告,但我不明白它在告诉我什么:
警告:从 'char *' 对 'char' 的赋值使指针变成整数而无需强制转换 [-Wint-conversion] 22 | dict[i][j]=word_scanned;
#include <stdio.h>
#include <stdlib.h>
int main() {
char word_scanned[50];
char dict[102402][50];
int i,j;
FILE *fptr;
if ((fptr = fopen("/usr/share/dict/words", "r")) == NULL) {
printf("Error! opening file\n");
// Program exits if file pointer returns NULL.
exit(1);
}
for(i=0; !feof(fptr); i++){
fscanf(fptr,"%s", word_scanned);
for (j=0; j<50; j++){
dict[i][j]=word_scanned;
}
}
printf("%s\n",dict[9]);
fclose(fptr);
return 0;
}
解决方案
dict[i][j]=word_scanned[j];
是答案。
但也阅读了有关 strncpy 的信息,而且仅供参考fscanf(fptr,"%s", word_scanned);
并不比直接扫描更安全,fscanf(fptr,"%s", dict[i]);
因为 word_scanned 也是 50 字节长。任何超过 50 个字符的字符串都会导致内存错误,因此这个额外的缓冲区根本没有帮助。
推荐阅读
- amazon-web-services - AWS sagemaker 本地 IDE + pytorch 估算器培训管理 conda 环境
- ffmpeg - 使用 FFMPeg 进行动态音量混合
- .htaccess - htaccess 重定向基于未登录的用户登录
- python - 如何删除 setToolTip 中的背景图片?
- node.js - 无法使用 mongoose 获取数据,即使我已经有了 db 和 collection
- javascript - chrome.windows.getAll() 等待迭代并发送响应
- excel - 如何在给定多个搜索条件的列中搜索并返回所有匹配项?
- html - 如何在 flex wrap 中尽可能多地占用空间
- kubernetes - 排查 Kubernetes 入口问题
- cypher - Cypher - 重复合并节点直到没有节点