I have a union of two std::vectors and when I call push_back i get a read access violation. I'm pretty new to unions so I bet I'm doing something wrong with them. Any ideas why this is happening?
struct Row
{
char order_id[30];
char garbage[994];
Row() {}
~Row() {}
};
struct Row_List
{
union
{
std::vector<Row> divided_row;
std::vector<char*> combined_row;
};
Row_List() {}
~Row_List() {}
};
int main(void)
{
Row_List results;
char current_row[1024];
//initialize row to null
for (int i = 0; i < 1024; ++i)
{
current_row[i] = '\0';
}
//error happens here
results.combined_row.push_back(current_row);
return 0;
}
EDIT: my final overall goal is to simplify the SQLGetData (in SQL.h) method by getting it to write the results into a vector of Row. currently, you just have to give it a pointer and it will write the results into that memory location. I wanted a function to return the result into a struct that I specify but each SQL query might have different fields in the result. I thought unions would let me write the results into a char array but then read it as a struct i specify.
I might run an SQL query that returns 10 rows and each row contains an integer and a char array. I might also run a query that returns 100 rows and each row contains a boolean, an integer, and two char arrays.
In the first example I want the results in a vector of structs which contain an integer and a char array. In the second example I want a results in a vector of structs that contain a boolean, an integer, and two char arrays.
The main issue being I want a generic way to write into any struct. I'm fine with passing a list of data type sizes though.
example function to do this:
bool SQL_Query::write_results(std::vector<std::array<char, 1024> >& results_vector)
{
/*
user makes a union of (a vector of long chars, and a vector of several small chars, ints etc.)
they pass the vector of long chars into this function
*/
//if not connected or if the query isnt successful or if the row structure hasnt been set then do nothing
if (!m_connected || !m_query_successful || !m_row_structure_set)
{
return false;
}
//for each row
while (SQLFetch(m_SQL_statement_handle) == SQL_SUCCESS)
{
//declare a single row
std::array<char, 1024> current_row;
//initialize row to null
for (int i = 0; i < 1024; ++i)
{
current_row[i] = '\0';
}
char* current_location = ¤t_row[0];
//for each column
for (unsigned int current_col = 1; current_col <= m_memory_size_list.size(); ++current_col)
{
//get next results max memory size
int current_buffer_size = m_memory_size_list.at(current_col - 1);
//write that into current_row at current_location
SQLGetData(m_SQL_statement_handle, current_col, SQL_C_DEFAULT, current_location, current_buffer_size, NULL);
//move to next write location in current_row by adding the current max memory size to
current_location += current_buffer_size;
}
//add single row to results vector
results_vector.push_back(current_row);
}
//return true if everything went right
return true;
}