C++中指向结构体指针向量的指针赋值代码报错问题咨询
Fixing the Pointer Dereference Error in Your Struct/Vector Code
Let's break down exactly why that line is failing, fix it, and also point out some potential pitfalls you might run into with this approach.
The Root Cause of the Error
Your problematic line is:
(*keys_)[size_]->(*value)[size] = inputValue; //此行报错
Here's what's wrong with the syntax:
(*keys_)[size_]correctly gives you aninfo*(a pointer to yourinfostruct instance).- To access the
valuemember of thatinfostruct, you need to use->value(since you're working with a pointer toinfo). This gives you astd::vector<int*>*—another pointer, this time pointing to a vector of integer pointers. - The invalid part is
(*value):valueis a member name of theinfostruct, not a standalone pointer variable. You can't dereference it directly like that. Instead, you need to first get the pointer to the vector via theinfostruct, then dereference that pointer to access the vector's elements.
The Fixed Code
Here's the corrected line:
(*(*keys_)[size_]->value)[size] = inputValue;
Or, to make the code much more readable (and easier to debug), split it into separate variables:
// Get the current info pointer from the keys vector info* currentInfo = (*keys_)[size_]; // Get the pointer to the value vector from the info struct std::vector<int*>* valueVector = currentInfo->value; // Dereference the vector pointer and assign the value (*valueVector)[size] = inputValue;
Important Additional Notes
While fixing the syntax will resolve the immediate error, there are some critical issues with this code structure you should address:
- Massive Memory Leak Risk: You're using raw pointers everywhere (
new std::vector<info*>,new info,new std::vector<int*>) without any correspondingdeletecalls. All this dynamically allocated memory will never be freed, leading to memory leaks. Consider switching to smart pointers likestd::unique_ptrorstd::shared_ptrto manage memory automatically, or better yet, use value types instead of pointers where possible (e.g., changestd::vector<int*>* valuetostd::vector<int*> valueunless you have a specific reason to use a pointer). - No Boundary Checking: Using
[]to access vector elements doesn't do any bounds checking. Ifsize_exceeds the size of*keys_, orsizeexceeds the size of*valueVector, you'll get undefined behavior (crashes, corrupted data, etc.). Usevector::at()instead if you want explicit out-of-bounds exceptions, or add your own checks before accessing elements. - Unnecessary Pointer Complexity: Most of these pointers are likely unnecessary. For example,
keys_could be astd::vector<info>(orstd::vector<std::unique_ptr<info>>) instead of a pointer to a vector of pointers. Reducing unnecessary indirection will make your code simpler, safer, and easier to maintain.
内容的提问来源于stack exchange,提问作者bgk1293
相关产品推荐
相关产品推荐

