• 0

[C] Change values of a struct within a function


Question

Hey guys, the snippet of code below is the definition of a struct called "Game" as well as a function that has been initialised, called "Game throwdice" for my uni project. I have two questions what does the struct function type do? Also I want to be able to update the values in the struct from within the function. I am not allowed to change the definition of the Game throwdice function to use pointers. How would I go about changing the values of the struct? My attempt at making this work is in the second code snippet:


// advance the game to the next turn,
typedef struct _game {
int diceScore;
int currentTurn;
} Game;
// assuming that the dice has just been rolled and produced diceScore
// the game starts in turn -1 (we call this state "Terra Nullis") and
// moves to turn 0 as soon as the first dice is thrown.
Game throwDice (Game g, int diceScore);
[/CODE]

My attempt at implementing this function:

[CODE]
Game throwDice (Game g, int diceScore){
g.diceScore=diceScore; //update the diceScore in the struct
g.currentTurn++; //advance the game to the next turn
return g;
}
[/CODE]

18 answers to this question

Recommended Posts

  • 0
  On 29/04/2012 at 04:14, ~Matt~ said:

what does the struct function type do?

I have absolutely no ideal what you intended with this question, therefore I cannot answer it. I assume that you are familiar with both structures and functions in C, and therefore didn't simply use the wrong terminology. If you would clarify, someone may be able to answer you.

  On 29/04/2012 at 04:14, ~Matt~ said:

How would I go about changing the values of the struct?

This question, on the other hand, is much more straight forward. If you are not allowed to change the function interface, I believe that you already have a workable implementation. Are you having any problems with it?

You can verify that your code works using the driver below.


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

// advance the game to the next turn,
typedef struct _game {
int diceScore;
int currentTurn;
} Game;

// assuming that the dice has just been rolled and produced diceScore
// the game starts in turn -1 (we call this state "Terra Nullis") and
// moves to turn 0 as soon as the first dice is thrown.
Game throwDice (Game g, int diceScore);

// initialize the structure to start the game
Game startGame (void);

Game throwDice (Game g, int diceScore) {
g.diceScore=diceScore; //update the diceScore in the struct
g.currentTurn++; //advance the game to the next turn
return g;
}

Game startGame (void) {
Game g;
g.diceScore=0;
g.currentTurn=-1;
return g;
}

int main (int argc, char * argv[]) {
Game g=startGame();
printf("Game diceScore = %d\nGame currentTurn = %d\n", g.diceScore, g.currentTurn);
srand(time(NULL));
g=throwDice(g, rand()%6+1);
printf("Game diceScore = %d\nGame currentTurn = %d\n", g.diceScore, g.currentTurn);
return 0;
}
[/CODE]

If you were allowed to modify the function prototype, this would be a much better (and more conventional) way to solve the problem:

[CODE]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// advance the game to the next turn,
typedef struct _game {
int diceScore;
int currentTurn;
} Game;

// assuming that the dice has just been rolled and produced diceScore
// the game starts in turn -1 (we call this state "Terra Nullis") and
// moves to turn 0 as soon as the first dice is thrown.
// returns -1 on failure and 0 on success
int throwDice (Game * g, int diceScore) {
if (!g) return -1;
g->diceScore=diceScore; //update the diceScore in the struct
g->currentTurn++; //advance the game to the next turn
return 0;
}

// Initialize a handle to start the game.
Game * startGame (void) {
Game * g=malloc(sizeof(Game));
g->diceScore=0;
g->currentTurn=-1;
return g;
}

// End the game by destroying its handle.
void endGame (Game * g) {
free( g );
}

int main (int argc, char * argv[]) {
Game * g=startGame();
printf("Game diceScore = %d\nGame currentTurn = %d\n", g->diceScore, g->currentTurn);
srand(time(NULL));
if (throwDice(g, rand()%6+1)<0) {
fprintf(stderr, "The game ended prematurely.\n");
endGame(g);
return -1;
}
printf("Game diceScore = %d\nGame currentTurn = %d\n", g->diceScore, g->currentTurn);
endGame(g);
return 0;
}
[/CODE]

I hope this satisfactorily answers your second question, at least.

  • 0

think of struct as a light weight class and is less expensive.

Unlike classes, structs can be instantiated without using the new. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. -- I think this was ur problem.

  • 0
  On 29/04/2012 at 05:49, still1 said:

think of struct as a light weight class and is less expensive.

Unlike classes, structs can be instantiated without using the new. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

This is C. There are no classes. And even if it wasn't C, I can't think of a language where anything of what you just said would be true. Certainly not C++; in C++ "class" is just an alternate keyword for "struct" and means the exact same thing.
  • 0
  On 29/04/2012 at 04:14, ~Matt~ said:

Hey guys, the snippet of code below is the definition of a struct called "Game" as well as a function that has been initialised, called "Game throwdice" for my uni project. I have two questions what does the struct function type do?

Functions are not "initialized", they are "defined" or "declared". I have no idea what you might mean by "struct function type". The code you posted featured a struct and a function.
  Quote
Also I want to be able to update the values in the struct from within the function. I am not allowed to change the definition of the Game throwdice function to use pointers. How would I go about changing the values of the struct?
You're not allowed to change the definition, but the values of an instance of that type, yes. Think of the type definition as a blueprint for creating instances: it defines what members each instance of "Game" will hold.

It's kind of strange that you ask that question when you do change the values of the struct in the very code you submitted, i.e. in the function throwDice. When you do:

Game g;

g.diceScore = something;

you are changing the value of the member diceScore of the instance "g" of your struct Game. So you seem to already know how to achieve what you want. I'm probably not understanding what your real question is, but it's hard to tell.

  • 0
  On 29/04/2012 at 06:28, Dr_Asik said:

This is C. There are no classes. And even if it wasn't C, I can't think of a language where anything of what you just said would be true. Certainly not C++; in C++ "class" is just an alternate keyword for "struct" and means the exact same thing.

C#

Just trying to help Op and not finding wrong with everything without looking just like what you are doing.

It was my bad thinking that it was c#

  • 0
  On 29/04/2012 at 06:39, Dr_Asik said:

I have no idea what you might mean by "struct function type".

By struct function type, I was just wondering what the difference is/was when declaring a function with

Game throwDice (Game g, int diceScore);[/CODE]

rather than:

[CODE]int throwDice (Game g, int diceScore) ;[/CODE]

It appears that I still do not know what my problem was/is. When I run xorangekiller's implementation of my function it works but when I try write my own the values still don't change:

[CODE]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct _game {
int diceScore;
int currentTurn;
} Game;
Game throwDice(Game g, int diceScore);
Game throwDice(Game g, int diceScore){
g.currentTurn++;
g.diceScore=diceScore;
return g;
}
int main (int argc, const char * argv[])
{
Game g;
srand((unsigned)time(NULL));
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
throwDice(g,rand()%6+1);
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
return 0;
}
[/CODE]

When I run the code I get this as the output:

[CODE]
0 is the turn AND 0 is the diceScore
0 is the turn AND 0 is the diceScore
[/CODE]

  • 0

Why don't you pass the Game object by a pointer and then modify it?

void throwDice(Game * g, int diceScore)
{
		g-&gt;currentTurn++;
		g-&gt;diceScore=diceScore;
}

and then

Game g;
throwDice(&amp;g, rand()%6+1);

Also make sure you perform some initialisation on g before you pass it to throw dice

Edit:

Also the difference between those functions is the return type. One returns an int, the other returns a Game.

  • 0
  On 29/04/2012 at 07:01, ~Matt~ said:

It appears that I still do not know what my problem was/is. When I run xorangekiller's implementation of my function it works but when I try write my own the values still don't change

You're avoiding using pointers by returning the modified Game object. The Game object you have in main() will never be changed by the function. In main, you need to set g equal to the returned value of throwDice(). That's how your copy will be changed. If you don't save the return value of throwDice() - basically, what you have done - then nothing will happen to g.

Basically, your code:


int main (int argc, const char * argv[])
{
Game g;
srand((unsigned)time(NULL));
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
throwDice(g,rand()%6+1);
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
return 0;
}
[/CODE]

Should be changed to:

[CODE]
int main (int argc, const char * argv[])
{
Game g;
srand((unsigned)time(NULL));
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
g = throwDice(g,rand()%6+1);
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
return 0;
}
[/CODE]

  • 0
  On 29/04/2012 at 07:01, ~Matt~ said:

By struct function type, I was just wondering what the difference is/was when declaring a function with

Game throwDice (Game g, int diceScore);[/CODE]

rather than:

[CODE]int throwDice (Game g, int diceScore) ;[/CODE]

1: If you dont know the diferrence there, I think there are bigger issues at hand.

2: If #1, folks, dont bring pointers into this :p

3: This is a uni project and you dont know #1?

I think there is something OP is not telling us, modifiy, etc

  • 0
  Quote
By struct function type, I was just wondering what the difference is/was when declaring a function with

Game throwDice (Game g, int diceScore);[/CODE]

rather than:

[CODE]int throwDice (Game g, int diceScore) ;[/CODE]

The difference is that the first version returns an int, whereas the second version returns a Game. The first term of a function signature is the return type.
  Quote
It appears that I still do not know what my problem was/is. When I run xorangekiller's implementation of my function it works but when I try write my own the values still don't change:

[CODE]#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct _game {
int diceScore;
int currentTurn;
} Game;
Game throwDice(Game g, int diceScore);
Game throwDice(Game g, int diceScore){
g.currentTurn++;
g.diceScore=diceScore;
return g;
}
int main (int argc, const char * argv[])
{
Game g;
srand((unsigned)time(NULL));
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
throwDice(g,rand()%6+1);
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
return 0;
}[/CODE]

That's a very good question and it's fundamental to understand this in C (and any programming language, really). Let's illustrate with a simple example:

[CODE]
void increment(int number) {
number = number + 1;
}

int main() {
int i = 0;
increment(i);
/* what is the value of i? */
}
[/CODE]

The value of i after the call to increment() is still 0, because the parameter "number" [b]is a copy[/b] of the original. Therefore, the copy is incremented, but the original keeps the same value.

So how can we change values using functions in C?? Simple solution: return the new value and assign it to the original variable. Let's illustrate:

[CODE]
int increment(int number) {
number = number + 1;
return number;
}

int main() {
int i = 0;
i = increment(i);
/* what is the value of i? */
}
[/CODE]

What happens here? A copy of i is passed to function increment under the name "number". number is incremented, and its value is returned. This value is then assigned to i, which is now therefore 1.

Notice that here we are copying the parameter into the function and copying it out again on the return. Copying an integer is very cheap, but for larger structures this gets expensive. This is where pointers come in: a pointer allows you to modify the original value without copying it. Example:

[CODE]
void increment(int* number) {
*number = *number + 1;
}

int main() {
int i = 0;
increment(&i);
/* what is the value of i? */
}
[/CODE]

The value of i after the call is 1, because instead of passing a copy of i, we passed a copy of its address in memory, i.e. a pointer. The function increment then accessed the value at that address and modified it (using the "*" notation). Therefore, the original value is modified without having been copied.

That was a basic presentation, you really should read a good tutorial or book on C to gain a solid understanding of these concepts. It's impossible to write any interesting program if you don't understand values vs pointers.

  On 29/04/2012 at 06:59, still1 said:

C#

Just trying to help Op and not finding wrong with everything without looking just like what you are doing.

It was my bad thinking that it was c#

Sorry for sounding harsh, it was 2AM and I couldn't find sleep. I should stop posting at these hours. Anyway, I thought about C# but even then value types are not really "lightweight" classes, and reference types can also be unassigned - their default value is null rather than 0 or some other value. So I figured the comment was inaccurate regardless of language and that apparently irritated me to no end.
  • 0
  On 29/04/2012 at 07:01, ~Matt~ said:

By struct function type, I was just wondering what the difference is/was when declaring a function with

Game throwDice (Game g, int diceScore);[/CODE]

rather than:

[CODE]int throwDice (Game g, int diceScore) ;[/CODE]

It appears that I still do not know what my problem was/is. When I run xorangekiller's implementation of my function it works but when I try write my own the values still don't change:

Based on your last post, I think that your problem is that you are missing some of the subtleties of C. Like rfirth pointed out above, the reason that my implementation works and yours does not entirely comes down to the fact that I was saving the return value and you were not. Notice the difference between the two code snipets below. The former is your implementation and the latter is mine.

[CODE]
throwDice(g,rand()%6+1);
[/CODE]

[CODE]
g = throwDice(g,rand()%6+1);
[/CODE]

However, like I stated in my earlier post, that is not really a good way to do it. What you are actually doing is creating multiple instances of your structure rather than working with just one and reassigning its variables directly (such as my pointer implementation). Therefore, your confusion as to the reason why the function returning the Game type would work but the one returning an int would not is probably due to a misconception on your part about what C is actually doing when you pass an argument to a function. When you pass g to throwDice() as the first argument, a copy of g is created to be used within throwDice(). Hence, when you change g.currentTurn and g.diceScore within the function, only the local copy is changed. The reason that it works when you return your local instance of g is because you are returning another copy of throwDice()'s local instance of g and setting the original instance of g in main() equal to it.

The function would work the way you most likely assume that it should if you passed g to throwDice() by reference. In that case, you would not have a local copy of g, but would, instead, be directly modifying the values within your instance of g in main(). (NOTE: this is only valid in C++, not in C. In C, you need to use pointers (as in my earlier post) to accomplish the same thing.) The driver below demonstrates pass by reference (in C++, there is no such concept in C).

[CODE]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// advance the game to the next turn,
typedef struct _game {
int diceScore;
int currentTurn;
} Game;

// assuming that the dice has just been rolled and produced diceScore
// the game starts in turn -1 (we call this state "Terra Nullis") and
// moves to turn 0 as soon as the first dice is thrown.
// returns -1 on failure and 0 on success
int throwDice (Game &g, int diceScore);

// initialize the structure to start the game
void startGame (Game &g);

int throwDice (Game &g, int diceScore) {
if (diceScore<1 || diceScore>6) return -1;
g.diceScore=diceScore; // update the diceScore in the struct
g.currentTurn++; // advance the game to the next turn
return 0;
}

void startGame (Game &g) {
g.diceScore=0;
g.currentTurn=-1;
}

int main (int argc, char * argv[]) {
Game g;
startGame(g);
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
srand(time (NULL));
if (throwDice(g, rand()%6+1)<0) {
fprintf(stderr, "The game ended prematurely.\n");
return -1;
}
printf("%d is the turn AND %d is the diceScore\n",g.currentTurn, g.diceScore);
return 0;
}
[/CODE]

Edit: Ah! Dr_Asik beat me to it (and has a more thorough explanation). I concede defeat.

  • 0

Thanks for your time guys :)

Appreciated! I understand now. But for this task I am not allowed to change the declaration of the functions, so I cannot use pointers, I have to use the memory expensive way, but I will definitely try write the same function with pointers, for my own benefit!

  • 0
  On 30/04/2012 at 01:13, ~Matt~ said:

Thanks for your time guys :)

Appreciated! I understand now. But for this task I am not allowed to change the declaration of the functions, so I cannot use pointers, I have to use the memory expensive way, but I will definitely try write the same function with pointers, for my own benefit!

You can always declare the structure as a global variable and do it the cheap way memory-wise ;)

  • 0
  On 30/04/2012 at 13:30, gian said:

You can always declare the structure as a global variable and do it the cheap way memory-wise ;)

"Beware of the dark side. Globals, gotos; the dark side of the Force are they. Easily they flow, quick to join you in a fight. If once you start down the dark path, forever will it dominate your destiny, consume you it will.."

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Maybe the site will get out of dabbing into Identity Politics.
    • ASUS TUF Gaming A16 (2024): A capable gaming laptop with AI for $300 less by Paul Hill If you are in the market for a mid-range gaming laptop packed with AI features, check out the ASUS TUF Gaming A16 2024 laptop, which is now discounted by 19% to just $1,299. The list price of this laptop is $1,599.99, so you’re saving $300 by taking advantage of this deal. Inside are the AMD Ryzen AI 9 HX 370 processor, which supports Windows AI features such as Recall, and the Nvidia GeForce RTX 4060 GPU, which offers solid gaming performance at 1080p. What you get: Features and performance for gamers The ASUS TUF A16 includes a 16-inch display with a 16:10 aspect ratio. Its refresh rate is 165Hz to minimize lag, it supports Nvidia G-Sync, and it has a 2.5K resolution. Inside the device, we have the AMD Ryzen AI 9 HX 370 processor, Nvidia GeForce RTX 4060 GPU, 16GB of LPDDR5X RAM, and a 1TB PCIe Gen 4.0 SSD. A nice thing ASUS has taken into consideration with this laptop is durability. It is MIL-STD-810H certified, meaning it has passed durability tests. While the laptop is discounted, it’s not cheap, so knowing it’s durable is a plus. In terms of cooling, it features Arc Flow Fans, four exhaust vents, five head pipes, and an anti-dust filter. Combined, these will keep the laptop running cool, providing better gaming performance. As for sound, the A16 features Dolby Atmos, Hi-Res Audio, and two-way AI noise cancellation. All of this will make your gaming sessions more immersive, and the noise cancellation will ensure you can hear your teammate properly. The laptop runs Windows 11 and includes 3 months of PC Game Pass, so you can play games right away, and save some money given the rising cost of games. Who should buy this laptop? Buyers can expect solid performance from this laptop for its price point. With the fast SSD, AI-capable CPU, and decent graphics card, you can expect to get most school or work tasks done easily, and it should capably handle games up to 1080p. The cooling features are nice because they will prevent any performance degradation, and the MIL-STD-810H rating offers peace of mind related to durability. If you are seeking the cutting edge of gaming performance, this laptop may not be for you. Additionally, if you aren’t much of a gamer or a creator, this laptop could be overkill, and you’d get away with buying something cheaper. If you want to pick it up, check out the buying link below. ASUS TUF Gaming A16: $1,299 (Amazon US) / MSRP $1,599.99 This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • After Elon has been high as a kite IN the oval office on video, I don't think anyone can mention Hunter and it mean anything anymore. As far as I'm concerned, Elon wiped the Hunter laptop issue away. And Marge Traitor Green just used that laptop to show congress Hunter naked so that she could look at him more! That was horrible.
    • AI vibrators do the same thing now..... err wait....
  • Recent Achievements

    • Reacting Well
      Cole Multipass earned a badge
      Reacting Well
    • Reacting Well
      JLP earned a badge
      Reacting Well
    • Week One Done
      Rhydderch earned a badge
      Week One Done
    • Experienced
      dismuter went up a rank
      Experienced
    • One Month Later
      mevinyavin earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      695
    2. 2
      ATLien_0
      275
    3. 3
      Michael Scrip
      218
    4. 4
      +FloatingFatMan
      188
    5. 5
      Steven P.
      146
  • Tell a friend

    Love Neowin? Tell a friend!