creating array with dynamic size on a stack

Hi guys, I have a small inconvenience here trying to
create char array on a stack which would fit the key size.
The only way so far is to allocate it on the heap and delete it after,
is there anyway to get around this. I have tried using enums but no luck.


1
2
3
4
5
6
7
8
9
10
11
12
inline bool DBStoreBase::removeRecord( std::string& Key)
{
//  char cKey[Key.size()]; //Error Must have constant value

		char * cKey = new char[Key.size()]; // Ok but have to delete[]

		strcpy(cKey, Key.c_str());


		MDB_val key{ Key.size(), cKey };
		delete[] cKey;
}
You can use a std::vector.
1
2
3
4
5
6
inline bool DBStoreBase::removeRecord( std::string& Key)
{
		std::vector<char> cKey(Key.begin(), Key.end() + 1);

		MDB_val key{ Key.size(), cKey.data() };
}


Krulcifer Einfolk
According to this page, MDB_val expects a void * as the second argument.
https://fossies.org/dox/openldap-2.4.44/structMDB__val.html

Although I dislike it intensely, you can cast string's internal array to a void pointer.
1
2
3
4
5
inline bool DBStoreBase::removeRecord (std::string& Key)
{  void * vkey = reinterpret_cast<void *> (key.c_str());

  MDB_val key { Key.size(), vkey };
}


BTW, line 10 should have ), not a }.
Last edited on
1
2
3
4
5
typedef struct MDB_val {
	size_t		 mv_size;	/**< size of the data item */
	void		*mv_data;	/**< address of the data item */
} MDB_val;


No it does not allow as it is a void * ,

Line 10 should be '}' not ')' as it is a struct not a class and has not constructor.
Sorry I omitted this detail.

Please reread my edited post.
You can use a std::vector.

inline bool DBStoreBase::removeRecord( std::string& Key)
{
std::vector<char> cKey(Key.begin(), Key.end() + 1);

MDB_val key{ Key.size(), cKey.data() };
}


Krulcifer Einfolk


Thanks this does the job, just +1 gives error but cKey(Key.begin(), Key.end()); is good.



Although I dislike it intensely, you can cast string's internal array to a void pointer.

inline bool DBStoreBase::removeRecord (std::string& Key)
{ void * vkey = reinterpret_cast<void *> (key.c_str());

MDB_val key { Key.size(), vkey };
}



yep that`s efficient, reinterpret cast complains but const_cast also does the trick.


1
2
3
4
 
void * vkey =  const_cast<char *> (Key.c_str());

		MDB_val key{ cKey.size(), vkey };


Thank you both!
Topic archived. No new replies allowed.