0

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?

4
Contributors
6
Replies
20
Views
2 Years
Discussion Span
Last Post by jencas
0

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

0

"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?

0

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.

1

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.