![](/img/trans.png)
[英]Why we can't compare pointers which don't point to elements within the same array?
[英]Why don't the elements stay in the array?
在這段代碼中,我正在讀取一個由多行組成的文件。 每行有 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]);
確保將每個新行寫入數組中的新插槽。 稍后,在打印數組時,請確保讀取的行數不要超過以前存儲的行數。
這是您的起點,但還有幾件事可以改進。
unsigned i = 0;
for (i = 0; i<numofrows && fgets(line, sizeof(line), infile) != NULL; ++i) {
char* english = strtok(line, search); //this is the word of the left column
unsigned englength=strlen(english);//the length of the word
rows[i] = malloc((englength+1)*sizeof(char));
strcpy(rows[i], english);
}
for(unsigned j=0;j<i;j++){
printf("%s\n",rows[j]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.