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;