Dispute

This is a discussion on Dispute within the C Programming forums, part of the General Programming Boards category; what does this code do? Code: struct x { int a[5]; int b[5]; }; struct x y[10]; void rotate(void) { ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    2

    Dispute

    what does this code do?
    Code:
    struct x
    {
     int a[5];
     int b[5];
    };
    
    struct x y[10];
    
    void rotate(void)
    {
     int i;
     struct x temp;
    
     temp=y[9];
    
     for (i=9; i; i--)
      y[i]=y[i-1];
    
     y[0]=temp;
    }
    i thought the compiler copies the elements from y[i-1] to y[i] (just like memcpy()), my friend means the compiler changes only the references from y[i-1]->y[i]. or, in other case, what does y[i] supplies, the address of the element or the whole struct?

  2. #2
    King of the Internet Fahrenheit's Avatar
    Join Date
    Oct 2001
    Posts
    128
    EDIT: I had something, but I believe I misread the question. I'm not going to browse here at 3am anymore...

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    You are right, your friend is wrong
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    161
    You are correct. In this case, the compiler makes copies as it rotates the structs through the array.

    For your friend to be correct, it would have to look something like this:

    Code:
    struct x
    {
      int a[5];
      int b[5];
    };
    
    
    struct x *y[10];
    
    
    void rotate(void)
    {
     int i;
     struct x *temp;
    
     for(i=0; i<10; i++)
       y[i] = malloc(sizeof(struct x));
    
     temp=y[9];
    
     for (i=9; i; i--)
      y[i]=y[i-1];
    
     y[0]=temp;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Cockpit dispute :)
    By Carlos in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 06-13-2003, 07:32 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21