Some help with a C code

cshum00
1. I have this code

Code:
typedef struct linkedlist {struct linkedlist *next; key_t value;} queue;
const queue *tail;

queue *create_queue(key_t input) {
queue temp;
temp.next = NULL;
temp.value = input;
tail = &temp;

printf("%d\n", tail->value);

return &temp;
}

int main() {
queue *one;
one = create_queue(2);

printf("%d\n", one->value);
printf("%d\n", tail->value);

return(0);
}

2. What it does is to
creates a queue called "one" and inserts a value of "2" into it.
Then it prints the value.

The problem is that i have this queue pointer called "tail" which points at the tail of the queue. So when i create the queue (using create_queue function), it obviously will point at the first object. After the program leaves the create_queue functions and goes back to the main function; why the address which the tail pointer is pointing at is not right.

Why after leaving the create_queue function, the tail value changes?

The Attempt at a Solution

AUMathTutor
First off, scientists and engineers are the only ones who call something like this a "code". It is code, but it is a program. Just some general erudition type stuff. [/rant]

Secondly, your problem isn't that tail is pointing at the wrong thing; it's that the memory it is set to point at is local to the create_queue function. The memory address has no meaning outside of the create_queue function. To do what you're doing, you will have to allocate memory on the heap (see malloc).

So yeah, you need to be careful about global and local variables. That may not be something your instructor emphasizes if s/he was raised on FORTRAN, where all variables are global (and where this problem wouldn't happen, mind you).

cshum00
[rant]First off, scientists and engineers are the only ones who call something like this a "code". It is code, but it is a program. Just some general erudition type stuff. [/rant]

It will be a "program" when after being compiled and running. So what i presented you still is just a piece of "code". lol

Secondly, your problem isn't that tail is pointing at the wrong thing; it's that the memory it is set to point at is local to the create_queue function. The memory address has no meaning outside of the create_queue function. To do what you're doing, you will have to allocate memory on the heap (see malloc).

Right, how can i forget about that. (XD)

P.S.> Thanks for the quick reply.

AUMathTutor
It will be a "program" when after being compiled and running. So what i presented you still is just a piece of "code". lol
"Some help with a C code"

I guess you just made a typo. And no, program refers more directly to the code, not to process, which is what you're thinking. It is a piece of code, but it is not "a code". Just letting you in on some lingo so you don't make your software people snicker at you.

As for the rest, don't worry about it. Like I said, I doubt your instructor ever even made a big point out of it.