is there any way to move pointer, which is initialized in main() function, to first executable function and have it accessible in whole program?
Here's the code:
main function, where is pointer d initialized:
void main(){
int x;
deque *d;
d=(deque*)malloc(sizeof(deque));
initDeque(d);
and I want to move the pointer into function called initDeque()
void initDeque(deque *d){ //Create new deque
d->front=NULL;
d->rear=NULL;
}
Is it possible to move it?
If by "move the pointer" you mean that you want to move the variable declaration, then you can do that but it will become a local variable only accesible inside that function. Clearly not what you want.
You need to make it global, that will make it accessible from all scopes. Note that global variables are considered ugly and increase the risk of errors and generally make the code less clear.
With a global pointer it would look like this:
deque *d;
void initDeque(void)
{
d = malloc(sizeof *d);
d->front = d->rear = NULL;
}
Note that you shouldn't cast the return value of malloc() in C.
Also note that nobody would have a global variable named using a single lower-case letter. It's way to easy to confuse it with a local variable, so you should at least make the name more obvious, e.g. something like
deque *theDeque;
Create a static structure to store all you want share.
Create a function to allocate your deque. I don't know the size of deque perhaps you can take it on the stack instead of the heap.
static struct {
deque d*;
} _G;
void main(){
int x;
_G.d = deque_new();
}
deque *deque_new(void){
deque *d;
d = malloc(sizeof(deque));
d->front=NULL;
d->rear=NULL;
return d;
}
or with the stack
static struct {
deque d;
} _G;
void main(){
int x;
deque_init(&_G.d);
}
deque *deque_init(deque *d){
memset(d, 0, sizeof(*deque));
return d;
}
Related
Lets say I have this structure
typedef struct Stack
{
int firstPlayerScore;
int secondPlayerScore;
int gamesCount;
}Stack;
and this function to ini the values:
void initStack(Stack *g)
{
g->firstPlayerScore = 0;
g->secondPlayerScore = 0;
g->gamesCount = 0;
}
The problem is here, I need to be able to reset other values, but keep g.gamescount and add +1 each time gameStart function runs. Its probably a simple solution ,but I am starting to lose my mind, thank you.
void gameStart(int choice) {
Stack g;
initStack(&g);
++g.gamesCount; // this works only once, then is reset again to 0.
{
// do stuff
}
}
Cant do differently, since I believe Structure need to be inicialized. Maybe it is possible to inicialize only once somehow?
P.S I cant use global variables
Pass a pointer to the state to your function:
void gameStart(Stack *g, int choice) {
++g.gamesCount; // this works only once, then is reset again to 0.
{
// do stuff
}
}
Then inside main():
int main() {
Stack g;
initStack(&g);
gameStart(&g, 49);
}
You need to allocate memory for the struct Stack variable g. You do not need global variables, what you need is to just while declaring g you need to call malloc function to allocate memory of the size of the struct type. It looks like this:
void gameStart(int choice) {
Stack *g = (Stack *) malloc(sizeof(Stack));
initStack(g);
++g->gamesCount; // this works only once, then is reset again to 0.
{
// do stuff
}
}
Malloc returns you void *, so it is better to typecast to Stack *. Also, you need to create Stack *, as it is a struct type and requires pointer tpye.
Hope this will help you.
I am currently using the out of date open BGI library for C as that is what my uni wants us to do but I can't figure out how to use this function.
extern void getmousestate(g_mousestate *state);
Definition:
void getmousestate(g_mousestate * state)
{
CHECK_GRAPHCS_INITED
state->x = sharedStruct->mouseX;
state->y = sharedStruct->mouseY;
state->buttons = sharedStruct->mouseButton;
}
g_mousestate Definition:
typedef struct mousestate {
int x, y;
int buttons;
}g_mousestate;
sharedStruct definition:
static SHARED_STRUCT * sharedStruct;
SHARED_STRUCT Definition:
typedef struct
{
int mouseX, mouseY;
int mouseButton;
int keyCode;
int keyLetter;
int visualPage;
} SHARED_STRUCT;
The sort of thing I was trying to do to call:
g_mousestate *a;
getmousestate(a->x);
But I don't know what to initialize a to...
I assumed this function could tell me what position the mouse is in and what buttons are being pressed etc, but I can't figure out how to call the function properly. Very much a beginner here, any help would be appreciated.
OK, beginner, let's start. You want to do:
g_mousestate *a;
getmousestate(a->x);
to get the x-position of the mouse. First note that you have declared a as a pointer, but no memory has been allocated for it (it points to nothing yet). So first you must have memory for the g_mousestate object:
g_mousestate a;
getmousestate(&a);
Now a is no longer a pointer but an object and you pass a pointer to the getmousestate function by taking the address of a with the & operator ("address-of").
You need to do no more since, if you look at the definition of the function, you see that all members are filled in by it.
I'm reading a book on data structure in C.
I saw code like this in exercise,
This is structure declaration.
typedef struct node
{
int data;
struct node *next;
}node;
The Function declaration, which will head of the tree..
node * create (int n); // please explain this
create is a function
But can we write this?
int create (int n);
Which one to use and what is the advantage of former declaration of function?
node * create (int n);
Function is create which will accept one int argument [n] and will return a pointer to node.
int create (int n);
Function is create which will accept one int argument [n] and will return an int.
In your case, node is a typedef to a structure, clearly not an int. So, you cannot replace the first function prototype with the later one. They both have dirrerent return type. So, the comparison for advantage is pointless.
Which one to use -- depends on your need.
If you want your function to return a pointer [possibly a pointer to the the newly allocated node, (in success case, or NULL in failure case)], you need to use node * create (int n); You can later use the pointer to newly allocated node in the caller function.
If you want your function to return only a success or failure indication [maybe 1 and 0], then you can use int create (int n);
C allows to return a pointer from a function!
To do so, you can declare like this..
int * myFunction(int N)
{. . .}
Means it will take integer N as parameter and return a pointer of Type int.
Note :
Point to remember is that, it is not good idea to return the address
of a local variable to outside of the function so you would have to
define the local variable as static variable.
Like,
int * myFunction(int N) {
static int M[10]
....
return M;
}
Coming to your question...
node * create (int n);
Means function create will take integer parameter n and it will return a pointer to node.
So use,
node * create (int n); to return a pointer
And
int create (int n); to return a integer!!
Hope it helps!!
node * create (int n);
This function takes n as argument and returns a pointer of type node *. Here node is a structure which is defined as above and this function returns a pointer to this structure.
You should not use int as return type for this function since it is returning a pointer, not a value.
In C component selection, what is the benefit of structure-returning function? for example:
struct S {
int a, b;
} x;
Why is it that I can assign the above struct as a function as shown below, Is there any benefit of doing this?
extern struct S f(); /* Why is this neccesary? */
x = f(); /* Is this accurate */
Open my eyes on this guys.
It's just a function that happens to return a struct. There's nothing more to it than that. You wouldn't be surprised to see a function return an int, why be surprised when one returns a struct?
As an aside, the extern is superfluous here because that is the default storage class for functions.
It is useful so that you can return multiple values from a function.
For example, you can use it like this
struct Point {
int x;
int y;
};
struct Point getMousePos()
{
struct Point pos;
pos.x = 567;
pos.y = 343;
return pos;
}
int main()
{
struct Point mouse_pos = getMousePos();
printf("Mousepos %d,%d\n", mouse_pos.x, mouse_pos.y");
}
The function can be forward declared with extern (this would normally be done in a header file), so that other functions know its prototype i.e. its parameters and return type, even if the function is itself defined in another file.
If you get a copy of a struct instead of a pointer to it, you know that you never have to worry about free()ing it, or whether there are any data races where one thread is writing to the struct while another reads from it, or whether the pointer returned by the function will be invalidated by some action that might be outside of your control.
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.
So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?
This is my struct
struct Stack {
int *data;
int current_size;
int max_size;
int (*push)(int);
int (*pop)();
};
And as an example here's push
int push(int val) {
if(current_size == max_size -1)
return 0;
data[current_size] = val;
current_size++;
return 1;
}
As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.
Is this possible to overcome somehow?
There's no implicit this in C. Make it explicit:
int push(Stack* self, int val) {
if(self->current_size == self->max_size - 1)
return 0;
self->data[self->current_size] = val;
(self->current_size)++;
return 1;
}
You will of course have to pass the pointer to the struct into every call to push and similar methods.
This is essentially what the C++ compiler is doing for you when you define Stack as a class and push et al as methods.
The typical approach in C is to have functions expect this as the first parameter.
int push(Stack *self, int val)
{
if (self->current_size == self->max_size -1) return 0;
self->data[self->current_size++] = val;
return 1;
}
This has the added benefit that, unless you need polymorphism, you don't need to put the functions in the stack, because you could just call push(stack, 10) instead of stack->push(stack,10).
C doesn't work like that. It's not an object oriented language. Functions that manipulate data structures need to take a pointer to the structure as an argument.
In header file you can declare static this variable
static struct Stack *this;
And then in push method you can use this variable
static int push(int val) {
if(this->current_size == this->max_size - 1)
return 0;
this->data[this->current_size] = val;
(this->current_size)++;
return 1;
}
The caveat is you have to manually set this variable through some method before you want to invoke other methods, eg:
struct Stack {
struct Stack (*_this)(struct Stack *); // <-- we create this method
int *data;
int current_size;
int max_size;
int (*push)(int);
int (*pop)();
};
And then we can implement _this method as
static struct Stack *_this(struct Stack *that)
{
retrun this = that;
}
The example:
struct Stack stack1, stack2;
... some initialization ...
stack1->_this(&stack1)->push(0);
stack1->push(1);
stack1->push(2);
stack2->_this(&stack2);
stack2->push(10);
stack2->push(20);
Your function pointers aren't methods so they don't have any information about the calling object. The only way to do what you want is to either pass in a pointer to the object, or make that pointer global (the latter is not recommended).
Obviously you can have a Stack * member in the struct and then just initialize it with the address of the struct before you use the function pointers. Then make the Stack * a parameter on the function pointers.
Since your are going to have only one Stack structure (that you named stack, apparently), you could define it as a global variable. This would allow pop/push to refer to the stack variable directly.
You would do something like:
stack.current_size += 4;
or use the -> operator if you decide to declare stack as a memory pointer to Stack.