gpt4 book ai didi

c - 为什么元素不留在数组中?

转载 作者:太空狗 更新时间:2023-10-29 14:49:19 25 4
gpt4 key购买 nike

在这段代码中,我正在读取一个包含多行的文件。每行有 2 个单词,用\t 分隔。在读取文件时,我正在创建一个动态分配的表,该表由文件中左侧的单词列组成。问题是,数组行似乎只在循环中是正确的。当我尝试在循环外打印 rows[i] 时,元素消失了。对不起,如果我解释得不是很好,我是 C 语言的新手..!

char line[21];
int i=0;
FILE *infile=fopen("words.txt", "r");
if(infile == NULL){
printf("The Input File is Null! Please Re-Run the program.");
return 1;
}
int numofrows=11;
char **rows=malloc(sizeof(char*)*numofrows);
//read the file
while(fgets(line, sizeof(line), infile) != NULL) {
english = strtok(line, search); //this is the word of the left column
englength=strlen(english);//the length of the word
for(i=0;i<numofrows;i++){
rows[i] = malloc(11*sizeof(char));
strcpy(rows[i], english);
}
}
//this doesnt work
for(i=0;i<numofrows;i++){
printf(rows[i]);
}

最后一个 for 循环应该打印数组行中的每个单词,而不是打印任何内容。

最佳答案

您的语句 printf(rows[i]); 格式错误。试试 printf("%s", rows[i]);

关于c - 为什么元素不留在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com