• 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

    • Microsoft locks Windows 11 user out, shows how easy losing data from forced encryption is by Sayan Sen Back in March earlier this year, a new redesigned Microsoft Account sign-in was released with the intention to make it "more modern, simple, and secure." Microsoft also probably hopes that the revamp will help win some hearts since many dislike the Microsoft Account (MSA) quite a bit as they are forced to use the service during Windows 11 installation. Yes, signing in to the MSA is one of the several system requirements for Windows 11, and it is also the recommended way and it clearly does not like it when users opt for a Local account instead. Microsoft often highlights the benefits of an MSA as it points out the unified access users get across devices and services like Windows, Office, OneDrive, and Xbox, which can help in synchronization of files and settings for convenience. A Microsoft Account also stores the BitLocker encryption key which is crucial thing that all users who have encryption need to store securely. Back in May this year, we covered reports of users losing their data as a consequence of BitLocker key loss, and this is a real danger for many, given that Microsoft now enables automatic BitLocker encryption on Windows 11 24H2, that most users won't even be aware of. So in the case of loss of access to a Microsoft Account, an affected user can suddenly find that they have lost all their data and there may be no way to recover it according to Microsoft's terms. Such account lock-outs can happen as a Reddit user deus03690 found out. The frustrated user claims that Microsoft apparently "randomly" locked their account when they were dealing with multiple data drives. They explain: The user has good reason to be annoyed and frustrated at this, Microsoft's own official guidance about the Account lock says: "If you tried to sign in to your account and received a message that it's been locked, it's because activity associated with your account might violate our Terms of Use." The Terms of Use for MSA explain how Microsoft deals with a closed account. It states: Thus, this shows how users can be pretty much helpless if they get locked out of MSA or lose access to it. It also shows how over-reliance on cloud services on Windows 11, something which LibreOffice recently pointed out, can lead to additional data nightmares like losing all of your data due to forced BitLocker encryption that you may not even be aware of was there in the first place. The solution? Consider keeping your important data backed up locally on internal or external HDDs and SSDs or NAS solution, as only cloud storage is probably not the best decision.
    • I don't know, I haven't checked what changed in previous sockets. I agree that the 1156-1155-1151 succession was suspicious, with a reduction in pin count every time. Intel could do a better job of pre-allocating pins for future use. Another hypothesis is that the internal layout of their CPUs change, like the I/O is moved from one place to another on the chip, and they need to reorganize pins rather than having circuitry go into spaghetti mode to remain compatible. I agree that if AMD is able to maintain compatibility, Intel should be able to do the same, at least by reserving pins for future use and then using those pins when a need for them arises. However, I wouldn't say that AMD's products are entirely better. Intel's I/O now slightly edges out thanks to having double the bandwidth to the chipset and dedicated Thunderbolt lanes to the CPU. It seems that they could widen their lead with the next platform. NVMe SSDs have increased the need for PCIe lanes significantly, and AM5 has been pretty underwhelming in that regard, especially because the chipset connection is so narrow and gets saturated with just 1 gen 4 SSD, leaving the other chipset connectivity (Ethernet, Wi-Fi, audio, etc) to hope for any remaining bandwidth. Otherwise motherboard manufacturers could also make more x2 M.2 slots, those would be fast enough at gen 5 speeds and possibly at gen 4 speeds too.
  • Recent Achievements

    • Week One Done
      korostelev earned a badge
      Week One Done
    • Week One Done
      rozermack875 earned a badge
      Week One Done
    • Week One Done
      oneworldtechnologies earned a badge
      Week One Done
    • Veteran
      matthiew went up a rank
      Veteran
    • Enthusiast
      Motoman26 went up a rank
      Enthusiast
  • Popular Contributors

    1. 1
      +primortal
      675
    2. 2
      ATLien_0
      264
    3. 3
      Michael Scrip
      184
    4. 4
      +FloatingFatMan
      177
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!