【发布时间】:2015-06-04 04:07:36
【问题描述】:
我正在尝试创建一个代码,该代码从纺织品中读取数据,然后将数据存储到内存中,打印到屏幕上以便用户阅读,但它仍然保存在内存中以便您可以使用它对于程序的其余部分..
这是纺织品的样品
75
nevermind
nvm
not much
nm
no problem
np
people
ppl
talk to you later
ttyl
because
cuz
i don't know
idk
as soon as possible
asap
yeah
ya
how are you
hru
you
列表继续,如果包括第一个数字,它总共有 150 个单词,151 行。 75 用于告诉您有多少对。
无论如何,这是我到目前为止编写的代码,它使用了这个结构
typedef struct
{
char *English;
char *TextSpeak;
}Pair;
目前我写的代码是:
FILE *infile =fopen("dictionary.txt","r");
int phraseCounter;
fscanf(infile, "%i", &phraseCounter); //Now you have the number of phrase pairs
//Allocate memory
Pair *phrases=malloc(sizeof(Pair) * phraseCounter);
//Run loop
for(int i=0; i < phraseCounter; i++){
//Get the english word
phrases[i].English = malloc(sizeof(char));
fscanf(infile,"%s",phrases[i].English);
//run loop to read next line
for(int a=0; a < phraseCounter; a++){
phrases[i].TextSpeak = malloc(sizeof(char));
fscanf(infile,"%s",phrases[i].TextSpeak);
}
printf("%s - %s\n", phrases[i].English, phrases[i].TextSpeak);
}
fclose(infile);
for(int i=0; i < phraseCounter; i++)
free(phrases[i].English);
free(phrases);
我不断得到的输出是:
nevermind - atm
by - definitely
def -
-
-
-
-
-
它一直持续到 75 行。
现在我不确定是否应该使用二维数组,或者这是否可以接受。任何帮助将不胜感激!谢谢
【问题讨论】:
-
phrases[i].English = malloc(sizeof(char));,你能解释一下你认为这是做什么的吗? -
为变量分配足够的内存?
-
这总是分配一个字节。
-
您找到问题的答案了吗?如果是这样,您应该考虑将最适合您的答案标记为已接受。
标签: c arrays memory file-io struct