我遇到的问题是,我在主体外部设置的函数值不会保留在结构中。我可能没有很好地描述这个,所以我将展示程序和结果并解释我想要的内容
struct Satellite
{
char countries[30];
int package;
int priceperpackage;
int timetransmission;
int requestedTransmission;
};
struct Satellite Satellite1;
struct Satellite Satellite2;
struct Satellite Satellite3;
struct Satellite Satellite4;
struct Satellite Satellite5;
void functionInput(void)
{
/*Country 1*/
strcpy(Satellite1.countries, "USA");
/*Country 2*/
strcpy(Satellite2.countries, "China");
/*Country 3*/
strcpy(Satellite3.countries, "Germany");
/*Country 4*/
strcpy(Satellite4.countries, "Japan");
/*Country 5*/
strcpy(Satellite5.countries, "Switzerland");
}
void printItems( struct Satellite satellite );
void assignValues( struct Satellite satellite );
int main(void)
{
functionInput();
assignValues ( Satellite1 );
assignValues ( Satellite2 );
assignValues ( Satellite3 );
assignValues ( Satellite4 );
assignValues ( Satellite5 );
printItems ( Satellite1 );
printItems ( Satellite2 );
printItems ( Satellite3 );
printItems ( Satellite4 );
printItems ( Satellite5 );
return 0;
}
void printItems( struct Satellite satellite )
{
printf( "%s\t\t %d\t\t %d\t\t %d\t\t %d\n", satellite.countries,satellite.requestedTransmission,satellite.package,satellite.priceperpackage,sat llite.timetransmission);
}
void assignValues( struct Satellite satellite )
{
satellite.requestedTransmission = (rand()% 2);
satellite.requestedTransmission = (rand()% 4 +1);
printf( "%s\t\t %d\t\t %d\t\t %d\t\t %d\n", satellite.countries,satellite.requestedTransmission,satellite.package,satellite.priceperpackage,sate llite.timetransmission);
}
这是输出
USA 4 0 0 0
China 1 0 0 0
Germany 1 0 0 0
Japan 3 0 0 0
Switzerland 1 0 0 0
USA 0 0 0 0
China 0 0 0 0
Germany 0 0 0 0
Japan 0 0 0 0
Switzerland 0 0 0 0
因为同一个东西没有打印两次,所以assignValues函数中的值不会保留在struct中。
答案 0 :(得分:1)
功能:
void assignValues( struct Satellite satellite )
应该是:
void assignValues( struct Satellite *satellite )
{
satellite->requestedTransmission = (rand()% 2);
等,你可以通过写assignValues( &satellite1 );
等来称呼它。这就是您如何表示希望assignValues
对名为satellite1
的对象进行操作的方式。
您最初编写代码的方式是,它会创建satellite1
的副本,并将该副本发送到assignValues
。对副本所做的更改不会影响原件。