help on copying arrays

This is a discussion on help on copying arrays within the C Programming forums, part of the General Programming Boards category; Code: typedef struct { char Jump[ 3 ]; char Manufacturer[ 8 ]; char BytesPerSector[ 2 ]; } Disk; in a ...

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    9

    help on copying arrays

    Code:
     
    typedef struct
    {
    	char 	Jump[ 3 ];
    	char 	Manufacturer[ 8 ];
    	char 	BytesPerSector[ 2 ];
    } Disk;
    in a funtion, there is this

    Disk *theDisk
    char array[40]={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', .....};

    the problem is how do i copy the 3rd element to 8th element of array to the the member ( thDisk->Manufacturer ) of structure Disk?
    and then display it on the screen.

    thx for the help

  2. #2
    Has a Masters in B.S.
    Join Date
    Aug 2001
    Posts
    2,267
    Code:
    #include <stdio.h>
    #include <string.h>
    
    typedef struct
    {
    char Jump[ 3 ];
    char Manufacturer[ 8 ];
    char BytesPerSector[ 2 ];
    } Disk;
    
    // if you use a pointer it must point to something before its used.
    Disk* theDisk;
    char array[40]={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', ...};
    
    // make theDisk point to a valid instance of Disk
    memcpy(theDisk->Manufacturer, &array[3], 5);
    ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.

  3. #3
    Registered User
    Join Date
    Jun 2002
    Posts
    9
    thx man
    that is helped a lot.

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Don't forget, if you're going to use manufacturer as a string, it'll need to be null terminated. I'm guessing the struct is initialised to 0, as per your other thread (if I remember right)? ... which means it'll work OK.

    Also, this is close:
    >memcpy(theDisk->Manufacturer, &array[3], 5);
    but the request was to start at the third element, whereas this starts at the 4th (the index count starts at 0, not 1).

    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying 2-d arrays
    By Holtzy in forum C++ Programming
    Replies: 11
    Last Post: 03-14-2008, 03:44 PM
  2. Is this poor coding? copying arrays of doubles
    By Hansie in forum C Programming
    Replies: 12
    Last Post: 05-25-2007, 02:34 PM
  3. copying strings to heap character arrays
    By SkyRaign in forum C++ Programming
    Replies: 4
    Last Post: 11-26-2006, 01:08 PM
  4. Copying Arrays
    By conright in forum C++ Programming
    Replies: 5
    Last Post: 01-22-2003, 03:09 PM
  5. copying character arrays
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 04-20-2002, 05:39 PM

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