array problem

This is a discussion on array problem within the C++ Programming forums, part of the General Programming Boards category; Hi All, I have a question about 1D arrays. if I have an array structure like this: ABCD EFGH IJKLM ...

  1. #1
    Registered User
    Join Date
    Feb 2004
    Posts
    2

    array problem

    Hi All,

    I have a question about 1D arrays.

    if I have an array structure like this:

    ABCD
    EFGH
    IJKLM

    and I want to create from that, this array:

    AABBCCDD
    AABBCCDD
    EEFFGGHH
    EEFFGGHH
    IIJJKKLLMM

    where the elements, row and columns are doubled?

    How do I start? Here's what I did, and its wrong.

    Code:
                    
                    numpix = height * width;
    
                    unsigned char* pixdata = new unsigned char[numpix];
    
    	 inFile.read((char *) pixdata, numpix);
         
    	
    	 for(int i = 0; i < numpix*2; i++)
    	 {
    	 cout << (unsigned int)pixdata[i] << endl;
    	 cout << (unsigned int)pixdata[i] << endl;
    	 }



  2. #2
    Registered User
    Join Date
    Feb 2004
    Posts
    46
    The simplest method would be to dynamically allocate a second array that is twice the size of the base. Then, using two index variables, walk down the base array. For every element in the base array, place two in the modified array. Then increment the base index by one and the modified index by two. Translated into C++, the algorithm is thus.
    Code:
    #include <iostream>
    
    using std::cout;
    using std::endl;
    
    int main()
    {
        char base[] = "ABCDEFGHIJKLM";
        char *modified = new char[sizeof base * 2 - 1];
        size_t j = 0;
    
        for (size_t i = 0; base[i] != '\0'; i++, j += 2)
            modified[j] = modified[j + 1] = base[i];
        modified[j] = '\0';
        cout<< modified <<endl;
    
        delete [] modified;
    }

  3. #3
    Registered User
    Join Date
    Feb 2004
    Posts
    2

    Smile Thanks, I will try it

    Thank you for your suggestion, will do.

    --Cman

  4. #4
    Registered User
    Join Date
    Sep 2003
    Posts
    135
    If your compiler complains about size_t, include <cstddef>.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array problem
    By TomBoyRacer in forum C++ Programming
    Replies: 3
    Last Post: 04-08-2007, 11:35 AM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Replies: 6
    Last Post: 02-15-2005, 10:20 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Need desperate help with two dimensional array problem
    By webvigator2k in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2003, 02:28 PM

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