Hello,

A simple program I am writing uses a struct to store a key and key size variable. However I get an error that states that my struct variable is being used without being initialized... I dont really know why it is telling me that.

Code:
keygen.hpp

#include <ctime>
#include <cstdlib>
#include <string>

#define KEY_SIZE_128 16
#define KEY_SIZE_192 24
#define KEY_SIZE_256 32

#define KEYBOARD_CHARS "`1234567890-=+_)(*&^%$#@!~[]\\|}{"

typedef struct KeyInfo {
    char Key[32];
    int KeySize;
};

/* Generates a random key. */
void GenerateKey(KeyInfo keyInfo, int keySize);

keygen.cpp

#include "keygen.hpp"

/* Generates a random key. */
void GenerateKey(KeyInfo keyInfo, int keySize)
{
    int random;
    time_t ltime;

    keyInfo.KeySize = keySize;

    srand(time(&ltime));

    for (int i = 0; i < keySize; i++)
    {
        random = rand() % strlen(KEYBOARD_CHARS) + 1;
        keyInfo.Key[i] = KEYBOARD_CHARS[random];
    }
}

main.cpp

#include <iostream>

using namespace std;

#include "keygen.hpp"

int main()
{
    struct KeyInfo key;

    GenerateKey(key, KEY_SIZE_128);

    for (int i = 0; i < key.KeySize; i++)
        cout << key.Key[i] << " ";

    cin.get();
}

How do I initialize a struct then?

Recommended Answers

All 6 Replies

How do I initialize a struct then?

Same way as everything else. Give it some values.

But I am doing that. keyInfo.KeySize = keySize; keyInfo.Key[i] = KEYBOARD_CHARS[random];

"My struct variable" means key, right?

The compiler message (I get a warning, not an error) is showing up because you declare it and then pass it as a parameter immediately thereafter:

struct KeyInfo key;

GenerateKey(key, KEY_SIZE_128);

But look at the declaration of GenerateKey:

void GenerateKey(KeyInfo keyInfo, int keySize);

You're passing keyInfo by value, which is not what you want, judging by GenerateKey - as written, you'll never get anything back.

Change GenerateKey to take keyInfo as a pointer or a reference, and that should take care of it.

While we're here...

typedef struct KeyInfo
{
    char Key[32];
    int KeySize;
};

Do you expect KeySize to always be 32 or less?

Yes, keySize will always be 32, 24 or 16.

The first time you are using it is when you pass it to the function GenerateKey. That's what your compiler doesn't like. That you are creating a variable, and then using it (i.e. passing it to a function) without initialising it.

Member Avatar for jencas

Hint: a struct in C++ is a class with all public members. So a struct can have a c'tor as well.

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.