Thread: Copying function problem

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    7

    Copying function problem

    Hi all,

    I am writing a function to copy one struct(called instruction) to another
    Code:
    void copy_struct(instruction src,instruction dest)
    {
    dest.inst_addr = src.inst_addr;
    dest.inst_func = src.inst_func ;
    dest.inst_destreg = src.inst_destreg;
    dest.src1 = src.src1;
    dest.src2 = src.src2;
    }
    copy_struct(instruction1,instruction2)
    But when I call copy_struct(instruction1,instruction2) it is not getting copied. Do I have to declare it as pointers or something in the fuction? Please help me fix the problem.

  2. #2
    Registered User
    Join Date
    Feb 2010
    Posts
    36
    Yeah ronrardin,you're correct.You need to pass the arguments to copy_function as pointers.Then only the changes done will be get affected after you return from the function.Else,the structure values will be copied and the values will be lost after the function scope ends.

  3. #3
    Registered User ungalnanban's Avatar
    Join Date
    Feb 2010
    Location
    Chenai
    Posts
    12

    Thumbs up

    no need to assign all the values. you need to send two pointers to the function that will copy the structure.

    Code:
    void copy_struct(instruction *src, instruction *dest)
    {
     *dest=*src;
    }

    See the Example:

    Code:
    #include<stdio.h>
    
    typedef struct
    {
            int inst_addr;
    }instruction;
    
    void copy_struct(instruction *src,instruction *dest)
    {
            *src=*dest;
    }
    
    
    int main()
    {
            int addr = 1000;
            instruction check1;
            instruction check2;
    
            check1.inst_addr = 10;
            check2.inst_addr = 50;
            printf("One: %d\n",check1.inst_addr);
            printf("Two: %d\n",check2.inst_addr);
            copy_struct(&check1,&check2);
            printf("One: %d\n",check1.inst_addr);
            printf("Two: %d\n",check2.inst_addr);
    }
    Output:
    One: 10
    Two: 50
    One: 50
    Two: 50
    Last edited by ungalnanban; 03-04-2010 at 01:11 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Tough problem with function pointers
    By Montejo in forum C Programming
    Replies: 10
    Last Post: 12-22-2009, 01:17 AM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. Problem with function pointers
    By vNvNation in forum C++ Programming
    Replies: 4
    Last Post: 06-13-2004, 06:49 AM
  5. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM