Thread: problem with structures

  1. #1
    Registered User baffleddreams's Avatar
    Join Date
    Aug 2010
    Location
    India
    Posts
    15

    problem with structures

    in structures can we swap two structure variables as such?like for example:
    say i create a structure called book and i want to arrange the books in ascending order depending on the book name.i.e.,the contents like price and the number of pages should get swapped along with the name:

    struct book
    {
    char name[10];
    char author[10];
    int pages;
    float price;
    }b[20];

    here i am asking if we can swap b[1] as such along with its contents with b[3],instead of going variable by variable: b[1].name with b[3].name

  2. #2
    Registered User \007's Avatar
    Join Date
    Dec 2010
    Posts
    179
    When in doubt, try it and see.

    Code:
    #include <stdio.h>
    
    struct book{
      int x;
    } a[3];
    
    int main(){
      a[0].x = 0;
      a[1].x = 1;
    
      a[0] = a[1];
      printf("a[0].x: %d\na[1].x: %d\n", a[0].x, a[1].x);
    
      return 0;
    }
    OUTPUT:

    $ ~/a.out
    a[0].x: 1
    a[1].x: 1
    Last edited by \007; 01-06-2011 at 11:24 AM.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by baffleddreams View Post
    in structures can we swap two structure variables as such?like for example:
    say i create a structure called book and i want to arrange the books in ascending order depending on the book name.i.e.,the contents like price and the number of pages should get swapped along with the name:

    struct book
    {
    char name[10];
    char author[10];
    int pages;
    float price;
    }b[20];

    here i am asking if we can swap b[1] as such along with its contents with b[3],instead of going variable by variable: b[1].name with b[3].name
    Yep. You can.

    Code:
    struct book {
      char name[20];
      char author[20];
      int pages;
      float price;
      } 
    
    struct book books[200];
    struct book temp.
    
    // swap
    temp = books[35];
    books[35] = books[131];
    books[131] =  temp;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with structures and seg fault
    By grifan526 in forum C Programming
    Replies: 3
    Last Post: 04-15-2010, 05:29 PM
  2. Problem filling an array of structures
    By bluetxxth in forum C Programming
    Replies: 7
    Last Post: 03-11-2010, 02:29 AM
  3. Getting illegal case error
    By scmurphy64 in forum C Programming
    Replies: 2
    Last Post: 09-17-2009, 10:35 AM
  4. Replies: 26
    Last Post: 06-11-2009, 11:27 AM
  5. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM