Could someone help me clear some confusions about pointers? in C - c

What i understand right now is.
int a = 100;
int *a_ptr; // creates pointer variable named a_ptr and points to type int
a_ptr = &a; // a_ptr is address of a
*a_ptr = 5; // value of pointer = value of a now set to 5.
What i dont understand is the point of pointers is to occupy the address of another variable as its right value or content isnt it?
if *a_ptr is the value shouldn't it be *a_ptr = &a;?
Thanks

Think of a pointer as a road sign: It tells you where you can find something. Nothing more, nothing less. The value/reason for pointers to exist is because it's a concept that we're actually all too familiar with. C passes everything by value. Let's use a far-fetched analogy that, I believe, will clear a couple of things up for you:
Imagine having been on holiday and telling someone about the hotel you stayed in. Instead of describing it in great detail, you'd give the other person the name, the address, and perhaps some more details that could help someone to find the place. You would not set about describing the entire thing in detail, nor would you tear the hotel down and take it with you, let alone rebuild it every time you tell somebody about it.
Back to C: C passes everything by value. In this analogy, that would be like handing everyone a 1-to-1 scale replica of the hotel you're raving on about. That's expensive, time consuming and really quite annoying. The people you've given a copy of the hotel to can change it, but you'd never know: there's a common starting point (the original hotel), but every copy is independent of one another after that.
Like in real life, you'd simply write the address of the hotel down and give that out to family and friends. That's what C does with pointers: it tells you where you can find something (a struct hotel or int), and others can use that address to travel to it.
The added benefit being that if some of your friends actually pay a visit to that place, they can tell you that it's changed in certain ways: the colour is now green, not blue, the owners have changed, etc...
Using the address allows everyone who has the address to have access to up-to-date information about the place.
If the hotel closes down, the address become pointless, but of course, if someone uses the address you gave them thinking they're going to stay in a great place, they'll get angry. What happens next is hard to predict (Undefined behaviour).
So in resuming:
int x = 123;// a hotel
int *x_address = &x;//an address to the hotel
int *for_friend = &x;
int *friend2 = &x; // you can hand out sever addresses to the same hotel
*x_address += 1; // read this as *(travel to)x_address to arrive at hotel X, and stay += 1 night or something
//friend2 wants to see how many nights were spent in hotel x:
printf("%d\n", *friend2);//124 -> 123 originaly + *x_address += 1
If x goes out of scope, that's the equivalent of the hotel closing. If sombody *x_address (travels to x), then their behaviour is undefined.
I've used different analogies in the past to explain in what way you can look at pointers to make them easier to understand, I've written this a while back, don't know if this makes things any clearer, but I thought I'd just post the link here:
Pointers are easy

if *a_ptr is the value shouldn't it be *a_ptr = &a;?
*a_ptr is the value, but &a is not the value, that is a pointer to the value, so they have different types.
So, the value can be set through the pointer, *a_ptr = a, or the pointer can be set to point at a value, a_ptr = &a.

Related

Is it possible to delete an element from a random position in a queue implemented in C?

I came across the following question and spent hours trying to figure out why there is a x in the remove function (I'm talking about question '(v)')
I see no reason for having a x because removing an element from the queue happens from the front and we already have the address of the front node stored (as a member in the struct).
It would be great if someone could please help me clear out this doubt because I tried to do so on my own but couldn't.
The next part of the question is as follows which is even more confusing...
The question is worded unclearly, but the main function you posted makes it clear what the code is supposed to do:
QueueElement seems to be a typedef to int, which is the value type stored in the queue.
Remove is supposed to remove the front element of the queue, and store its value into *x.
This is the case because in main it calls Remove(&i, &numqueue) and then prints the value of i.
As as aside, this code is badly written and hopefully you won't pick up too many bad habits from it. In particular, defining a Boolean where TRUE==0 and FALSE==1 is backwards and can lead to mistakes where if (bool_value) does the opposite of what it appears. This mistake actually happens in main where they wrote while (!QueueEmpty(...)).

Changing a pointer as a result of destroying an "object" in C

As part of a course I am attending at the moment, we are working in C with self-developed low level libraries, and we are now working in our final project, which is a game.
At a certain point, it seemed relevant to have a struct (serving as a sort of object) that held some important information about the current game status, namely a pointer to a player "object" (can't really call the simulated objects we are using actual objects, can we?).
It would go something like this:
typedef struct {
//Holds relevant information about game current state
state_st currstate;
//Buffer of events to process ('array of events')
//Needs to be pointers because of deallocating memory
event_st ** event_buffer;
//Indicates the size of the event buffer array above
unsigned int n_events_to_process;
//... Other members ...
//Pointer to a player (Pointer to allow allocation and deallocation)
Player * player;
//Flag that indicates if a player has been created
bool player_created;
} Game_Info;
The problem is the following:
If we are to stick to the design philosophy that is used in most of this course, we are to "abstract" these "objects" using functions like Game_Info * create_game_info() and destroy_game_info(Game_Info * gi_ptr) to act as constructors and destructors for these "objects" (also, "member functions" would be something like update_game_state(Game_Info * gi_ptr), acting like C++ by passing the normally implicit this as the first argument).
Therefore, as a way of detecting if the player object inside a Game_Info "instance" had already been deleted I am comparing the player pointer to NULL, since in all of the "destructors", after deallocating the memory I set the passed pointer to NULL, to show that the object was successfully deallocated.
This obviously causes a problem (which I did not detect at first, and thus the player_created bool flag that fixed it while I still was getting a grasp on what was happening) which is that because the pointer is passed by copy and not by reference, it is not set to NULL after the call to the "object" "destructor", and thus comparing it to NULL is not a reliable way to know if the pointer was deallocated.
I am writing this, then, to ask for input on what would be the best way to overcome this problem:
A flag to indicate if an "object" is "instanced" or not - using the flag instead of ptr == NULL in comparisons to assert if the "object" is "instanced" - the solution I am currently using
Passing a pointer to the pointer (calling the functions with &player instead of only player) - would enable setting to NULL
Setting the pointer to NULL one "level" above, after calling the "destructor"
Any other solution, since I am not very experienced in C and am probably overlooking an easier way to solve this problem.
Thank you for reading and for any advice you might be able to provide!
I am writing this, then, to ask for input on what would be the best way to overcome this problem: …
What would be the best way is primarily opinion-based, but of the ways you listed the worst is the first, where one has to keep two variables (pointer and flag) synchronized.
Any other solution…
Another solution would be using a macro, e. g.:
#define destroy_player(p) do { /* whatever cleanup needed */; free(p), p = NULL; } while (0)
…
destroy_player(gi_ptr->player);

Cant understand the game tree for Quarto game

I am going to implement quarto game in which each opponent choose the next step for another opponent but I am having trouble to draw min max node and understand which node is max and which is min? the only thing that came to my mind is this :
But I am pretty sure that something is wrong with that?
can anyone help?
Just to clarify, I'm assuming that at the top node P1 is choosing a piece for P2 to place, at the second node P2 is placing the piece, at the third node P2 is choosing a piece for P1 to place, and then at four P1 is placing that piece and so on.
I can see why you might think that you're doing something wrong, because this is not the way that minimax is conventionally set up, but this seems like a logical way to apply it for quarto. You are correctly assigning min and max turns and such, so I don't see anything inherently wrong with this setup. Keeping track of the choosing vs. placing nodes for the purposes of the evaluation function could potentially get tricky, but I think it should be doable. Have you encountered any obstacles with doing it this way? If not, I'd say to give it a shot. It's an interesting twist on standard minimax.

Get struct's size passed as void to function

I'm changing some codes in a database library. The way it works I send a void pointer, to get the size of it I call a query and using the query I calculate the size of the structure. Now the problem is I receive the struct as params but the function fails before/in the middle of the first fetch. After that I need to clear the structure, but I dont even have the size.
I know the best way is send the size of the structure as a param, but I have thousands and thousands programs already compiled, the library is from 1996, so I need to find a way to calculate the structure size even if the type is void.
One idea I had was to calculate the position of the next element that is not in the structure
0x000010 0x000042
[int|char[30]|int|int][int]
So the size is 32, because the 0x00042-0x000010 is 32.
Is there a way to know when I got out of the structure.
the prototype of the function is
int getData(char* fields, void* myStruct)
I need to find out the structure size.
Sorry if I missed some information, the code is HUGE and unfortunately I cannot post it here.
No, in general there's no way, given a void *, to figure out what you're after. The only thing you can do is compare it against NULL, which of course doesn't help here.
Note that there's nothing in the void * that even says it points at a struct, it could just as well be pointing into the middle of an array.
If you have some global means of recording the pointers before they're passed to getData(), you might be able to implement a look-up function that simply compares the pointer value against those previously recorded, but that's just using the pointer value as a key.

Returning multiple values from a C function

Important: Please see this very much related question: Return multiple values in C++.
I'm after how to do the same thing in ANSI C? Would you use a struct or pass the addresses of the params in the function? I'm after extremely efficient (fast) code (time and space), even at the cost of readability.
EDIT: Thanks for all the answers. Ok, I think I owe some explanation: I'm writing this book about a certain subset of algorithms for a particular domain. I have set myself the quite arbitrary goal of making the most efficient (time and space) implementations for all my algos to put up on the web, at the cost of readability and other stuff. That is in part the nature of my (general) question.
Answer: I hope I get this straight, from (possibly) fastest to more common-sensical (all of this a priori, i.e. without testing):
Store outvalues in global object (I would assume something like outvals[2]?), or
Pass outvalues as params in the function (foo(int in, int *out1, int *out2)), or
return a struct with both outvals, or
(3) only if the values are semantically related.
Does this make sense? If so, I think Jason's response is the closest, even though they all provide some piece of the "puzzle". Robert's is fine, but at this time semantics is not what I'm after (although his advice is duly noted).
Both ways are valid, certianly, but I would would consider the semantics (struct vs parameter reference) to decide which way best communicates you intentions to the programmer.
If the values you are returning are tightly coupled, then it is okay to return them as a structure. But, if you are simply creating artificial mechanism to return values together (as a struct), then you should use a parameter reference (i.e. pass the address of the variables) to return the values back to the calling function.
As Neil says, you need to judge it for yourself.
To avoid the cost of passing anything, use a global. Next best is a single structure passed by pointer/reference. After that are individual pointer/reference params.
However, if you have to pack data into the structure and then read it back out after the call, you may be better off passing individual parameters.
If you're not sure, just write a bit of quick test code using both approaches, execute each a few hundred thousand times, and time them to see which is best.
You have described the two possible solutions and your perceived performance constraint. Where you go from here is really up to you - we don't have enough information to make an informed judgement.
Easiest to read should be passed addresses in the function, and it should be fast also, pops and pushes are cheap:
void somefunction (int inval1, int inval2, int *outval1, int *outval2) {
int x = inval1;
int y = inval2;
// do some processing
*outval1 = x;
*outval2 = y;
return;
}
The fastest Q&D way that I can think of is to pass the values on a global object, this way you skip the stack operation just keep in mind that it won't be thread safe.
I think that when you return a struct pointer, you probably need to manually find some memory for that. Addresses in parameter list are allocated on the stack, which is way faster.
Keep in mind that sometimes is faster to pass parameters by value and update on return (or make local copies on the stack) than by reference... This is very evident with small structures or few parameters and lots of accesses.
This depends massively on your architecture, and also if you expect (or can have) the function inlined. I'd first write the code in the simplest way, and then worry about speed if that shows up as an expensive part of your code.
I would pass the address to a struct. If the information to be returned isn't complex, then just passing in the addresses to the values would work too.
Personally, it really comes down to how messy the interface would be.
void SomeFunction( ReturnStruct* myReturnVals )
{
// Fill in the values
}
// Do some stuff
ReturnStruct returnVals;
SomeFunction( &returnVals);
// Do more stuff
In either case, you're passing references, so performance should be similar. If there is a chance that the function never actually returns a value, you could avoid the cost of the malloc with the "return a struct" option since you'd simply return null.
My personal preference is to return a dynamically allocated (malloc'd) struct. I avoid using function arguments for output because I think it makes code more confusing and less maintainable in the long-term.
Returning a local copy of the structure is bad because if the struct was declared as non-static inside the function, it becomes null and void once you exit the function.
And to all the folks suggesting references, well the OP did say "C," and C doesn't have them (references).
And sweet feathery Jesus, can I wake up tomorrow and not have to see anything about the King of Flop on TV?

Resources