Home > Enterprise >  C Struct of array global scope
C Struct of array global scope

Time:05-24

I need a struct of array[lenght] to be seen by all my methods(global).

The problem I have is that the struct needs to be initialized with a specific length inside a specific function. To be more precise the initialization of struct with the length of size has to happen when importantFunction() is called and I need all my other fcts to have access to the struct.

This is the solution Ive come with. Im unaware of any other way to make the struct global.

Cant use the hashMap or vector class. This template is part of my own vector class.

template<class A>
class Table {
public:

    struct hash {
        T value;
        int key;
    };

    struct hash *hash1;
    //struct hash hash1[size]; I could do but I dont have access to size from here.

    private:
       A *elements;
       int size;
       int capacity;
};


template<class A>
Table<A>::Table(const Table &otro) {
    //function that will use the struct of array
}

template<class A>
void Table<A>::importantFunction() {
    hash1 = malloc(size);
    //struct hash hash1[size]; if I do this the scope of my struct hash1 is only whitin this function
}

CodePudding user response:

If using std::vector is not allowed, then you can use dynamic memory allocation either manually using new and delete or better would be to use smart pointers. But since you're not allowed to use std::vector, i suppose you're also not allowed to use smart pointers in your project.

template<class A>
class Table {
public:

    struct hash {
        T value;
        int key;
    };
//--------vvvvvvvv-------------->a pointer to a hash object
    hash *ptrArray = nullptr; 

    private:
       A *elements;
       int size;
       int capacity;
};

//other member functions here

template<class A>
void Table<A>::importantFunction() {
//-------------vvvvvvvvvvvvvvvv-->assign to ptrArray the pointer returned from new hash[size]() 
    ptrArray = new hash[size]();
    
}
//don't forget to use delete[] in the destructor
  • Related