【发布时间】:2019-11-17 16:21:07
【问题描述】:
#include<stdio.h>
struct mystruct{
int age; //age of child
int flag; //flag: if 1 then change the age, if 0 then don't
};
///////////////////////////////////////////////////////////////////////////////
void Change_Age_Of_First_Child(struct mystruct *child[]){ //parameter is a structure passed by reference
if (child[0]->flag==1){ //checking if flag of first child is 1
child[0]->age=0; //if it is 1 then change the age to 0
}
}
///////////////////////////////////////////////////////////////////////////////
int main(){
int x,i; //x is used to store the integer version of ch, i is loop counter
char ch; //used to store character from file
FILE *test;
test=fopen("test.txt","r+");
struct mystruct child[7];
for(i=0;i<7;i++){
ch=fgetc(test); //this ch is the age
x= ch - '0'; //saving integer version of ch
child[i].age=x; //saving x into age part of structure
ch=fgetc(test); //this ch is the flag
x= ch - '0'; //saving integer version of ch
child[i].flag=x; //saving x into flag part of structure
fseek(test,2,SEEK_CUR); //moving to next line of file for the consecutive loops
}
Change_Age_Of_First_Child(&child);
fclose(test);
printf("%d",child[0].age);
}
文件“test.txt”:
51
81
90
90
70
51
80
我正在尝试通过引用来学习传递结构。我制作了一个简单的测试程序,从文件中读取年龄和标志,并将其存储到名为 child 的数组中,该数组是一个结构。然后我将 child 作为引用传递给一个函数。在那个函数中,为了简单起见,我只检查 child 的第一个元素(其中包含文件第一行的数据)。如果标志为 1,则将年龄设置为 0。
但是,当我在主程序中打印第一个孩子的年龄时,它不起作用。事实上,控制台什么也没显示。它运行了一段时间,然后简单地说“进程退出”,这意味着程序已经完成。帮助将不胜感激。
注意:每行文件的第一个字符是年龄,第二个是标志。
【问题讨论】:
-
打开编译器的警告!它会告诉你不要通过
&child。 -
...而
*child[]是指向结构的指针数组,而不是指向结构数组的指针,即child[] -
@PaulOgilvie OP 不需要传递任何警告标志来获取警告,请参阅我的答案。 :)
-
是的,你错了。如果你的编译器没有告诉你,你应该把它扔掉,买、借或偷一个现代的。 Enable warnings and treat them as errors.
-
没有“启用警告”。在任何情况下,符合标准的编译器必须为此产生警告,除非您费力地抑制它们。您是否偶然使用了臭名昭著的糟糕的 Visual Studio Code?span>