如何将排序的结构返回到我的main函数?

时间:2016-09-25 20:09:54

标签: c function struct return

目标:对3个骰子的结构进行排序并返回已排序

#include <stdio.h>
#include <string.h>
#include <time.h>  

STRUCT

struct RolledDice
{
    int die1 ;
    int die2 ;
    int die3 ;
} dice;

原型

void sort_dice(struct RolledDice dice );

主要

int main() {
srand ( time(NULL) );

dice.die1 = rand() % 6 + 1 ;
dice.die2 = rand() % 6 + 1 ;
dice.die3 = rand() % 6 + 1 ;

sort_dice(dice);

return 0;
}

排序骰子功能

void sort_dice(struct RolledDice dice) {

    printf("Die 1: %d \n", dice.die1);
    printf("Die 2: %d \n", dice.die2);
    printf("Die 3: %d \n\n", dice.die3);

    int tempDie = 0;

(可能有更好的方法来做到这一点......但这是我能想到的最好的方法)

    while ( dice.die1 < dice.die2 || dice.die1 < dice.die3 || dice.die2 < dice.die3 )
    {
        if ( dice.die1 < dice.die2 )
         {
         tempDie = dice.die1 ;
         dice.die1 = dice.die2 ;
         dice.die2 = tempDie ;
         }
        if ( dice.die1 < dice.die3 )
         {
         tempDie = dice.die1 ;
         dice.die1 = dice.die3 ;
         dice.die3 = tempDie ;
         }
        if (dice.die2 < dice.die3 )
         {
         tempDie = dice.die2 ;
         dice.die2 = dice.die3 ;
         dice.die3 = tempDie ;
         }
    }

    printf( "Die 1: %d \n", dice.die1 );
    printf( "Die 2: %d \n", dice.die2 );
    printf( "Die 3: %d \n\n", dice.die3 );
}

我尝试将void更改为intstruct,但不断收到错误,或者无法更新struct中的main

1 个答案:

答案 0 :(得分:2)

您正在对dice结构的副本进行排序,该结构在函数返回时会在超出范围时丢失。

将您的功能更改为:

struct RolledDice sort_dice(struct RolledDice dice) {

最后只有return dice

用法:

int main() {
srand ( time(NULL) );

dice.die1 = rand() % 6 + 1 ;
dice.die2 = rand() % 6 + 1 ;
dice.die3 = rand() % 6 + 1 ;

dice = sort_dice(dice);

// print the sorted struct here
printf( "Die 1: %d \n", dice.die1 );
printf( "Die 2: %d \n", dice.die2 );
printf( "Die 3: %d \n\n", dice.die3 );  
return 0;
}

或者将dice作为指针传递,并在函数中使用dice->而不是dice.(重构更重,但内存副本更少,因此性能更高)

void sort_dice(struct RolledDice *dice) {
...
 dice->die1 = dice->die3 ;
...

用法:

int main() {
srand ( time(NULL) );

dice.die1 = rand() % 6 + 1 ;
dice.die2 = rand() % 6 + 1 ;
dice.die3 = rand() % 6 + 1 ;

sort_dice(&dice);  // pass as pointer so it can be modified in the function

// print the sorted struct here
printf( "Die 1: %d \n", dice.die1 );
printf( "Die 2: %d \n", dice.die2 );
printf( "Die 3: %d \n\n", dice.die3 );
return 0;
}

注意:您的原始代码会在排序例程中正确地打印出气泡排序值。我想问题是你没有找到在调用函数中更新它的方法(创建一个只打印排序值的函数是没用的)