Thread: Simple pointer function question

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    19

    Simple pointer function question

    Hi,

    I struggled on something; here is the question;

    I have a struct that contains some items and a pointer; I call this node;
    I have another node in same struct and also have a pointer.

    Now these two nodes are linked with a next pointer just as you know as linked list.

    I want to do move to another linked list from the first one. (temp is a struct pointer)

    Code:
    temp=firstnode;
    temp=temp->next;
    It is ok, but when I want to do this with a function;

    Code:
    void myfunction(mystruct *tmp)
    {
    tmp=tmp->next;
    }
    ...
    ..
    myfunction(temp); //in main(), call the function
    it fails, what am I missing? Isnt it already a "call by referance"? why doesnt temp move another node?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Mar 2012
    Posts
    19
    I tried this and worked, I don't know why;

    Code:
    void myfunction(mystruct **tmp)
    {
    *tmp=(*tmp)->next;
    }
    ..
    .
    ..
    myfunction(&temp); //in main(), call the function
    I really don't know what happened and why it worked, can someone explain how?

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    88
    Passing a pointer to a function, say a pointer to an integer variable, allows you to change the value of the integer variable pointed to by that pointer.

    In your first code you posted, you were passing a pointer (aka some variable), changing its value in the function, and then that changed nothing outside the scope of your function.

    // Corrections, comments welcomed.
    W7, Ubuntu -- mingw, gcc, g++, code::blocks, emacs, notepad++

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple pointer to function
    By Mentallic in forum C Programming
    Replies: 1
    Last Post: 10-17-2012, 04:58 AM
  2. Need help with simple function pointer
    By livin in forum C Programming
    Replies: 1
    Last Post: 12-01-2011, 09:00 PM
  3. Simple pointer question
    By jayznz in forum C Programming
    Replies: 2
    Last Post: 04-04-2006, 11:36 PM
  4. Simple Pointer Question
    By Reason58 in forum C Programming
    Replies: 2
    Last Post: 01-08-2004, 07:18 PM
  5. Very simple pointer question
    By Shadow12345 in forum C++ Programming
    Replies: 1
    Last Post: 06-17-2002, 11:56 AM