VernonDozier 2,218 Posting Expert Featured Poster

Here's the code. Uncomment line 9 and you get the following error.

ISO C++ forbids initialization in array new

Leave it commented out and it works just fine. I'm not sure why it has a problem with one but not the other. Each object is a 16 byte array. One just has a struct wrapper around it.

One, I'm confused and would like to understand what the problem is even though I appear to have a solution. Two, I have a bunch of code with lines like "key" from before I was trying to stick it into a vector. While it's not the end of the world to replace it with "key.bytes", I'd rather not and since "bytes" is the only element of the struct, I'd like to do away with the structure.

Three, I'm confused why lines 48 and 49 work. Seems like I'm missing an outer pair of brackets and they need to be this since it's an array WITHIN a struct. I expected to have to use this...


xtea_key_t key1 = {{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}};
xtea_key_t key2 = {(4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}};

which seems to also work. Note the single rather than double brackets in lines 48 and 49 compared with above. They're both OK?

#include <iostream>
#include <vector>
#include <cstdio>
#include <iomanip>
#include <stdint.h>
using namespace std;


//#define HAS_ERROR

#ifdef HAS_ERROR
typedef uint8_t xtea_key_t[16];
#else
struct xtea_key_t
{
    uint8_t bytes[16];
};
#endif


void print_key(const xtea_key_t& key)
{
    for(int i = 0; i < 16; i++)
    {
        #ifdef HAS_ERROR
        cout << hex << setw(2) << setfill('0') << (int) key[i] << ' ';
        #else
        cout << hex << setw(2) << setfill('0') << (int) key.bytes[i] << ' ';
        #endif
    }
}


void print_keys(const vector<xtea_key_t>& keys)
{
    for(int i = 0; i < keys.size(); i++)
    {
        cout << "Key " << i + 1 << " : ";
        print_key(keys[i]);
        cout << endl;
    }
}


int main()
{
    vector<xtea_key_t> keys;
    xtea_key_t key1 = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    xtea_key_t key2 = {4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
    keys.push_back(key1);
    keys.push_back(key2);
    print_keys(keys);
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.