• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Arrays inside structures in c++

Metalloid

Diamond Member
If have an array called array[] inside a struct called original such as

struct original
{
int array[]
};

Then in main I declare the struct, and I want to access a specific value of that array.
main()
original new;
int i=new.array[1];

Am I allowed to do that?
 
Ok thanks just making sure that I was allowed to ask for a specific variable in the array rather than the entire array.
 
The general idea of accessing array values when the array is declared within a structure is fine. Just be aware that your sample code isn't doing that ... it declares a zero-length array (no size between the brackets) and then later tries to access something in the 2nd position of the array, which will certainly result in memory corruption whether the array is inside of a structure or not. Hopefully you knew that and just mis-typed your example? Also, naming the instance of your struct as "new" isn't going to work too well in C++ since the "new" keyword is reserved.

If this is nitpicking then I apologize, but you must admit that the provided code sample is a little ambiguous. 🙂
 
Originally posted by: mysticfm
The general idea of accessing array values when the array is declared within a structure is fine. Just be aware that your sample code isn't doing that ... it declares a zero-length array (no size between the brackets) and then later tries to access something in the 2nd position of the array, which will certainly result in memory corruption whether the array is inside of a structure or not. Hopefully you knew that and just mis-typed your example? Also, naming the instance of your struct as "new" isn't going to work too well in C++ since the "new" keyword is reserved.

If this is nitpicking then I apologize, but you must admit that the provided code sample is a little ambiguous. 🙂

Yep, what he said.
Beyond that, consider using vector<int> instead of a raw array. Save yourself alot of headache, and gain alot of useful methods that you may have to write yourself.
 
remember to have a destructor for your struct if you change that array to a pointer to dynamically allocated memory.
 
Back
Top