Defining dynamic memory in C++ is different than defining dynamic memory in C. Whereas in C one must use
malloc()
and typecasting, C++ is a little different.
Just for clarity:
comps *components = (comps*)malloc(sizeof(comps)*10);
Yes, this memory does allocate correctly. However, when the function goes out of scope, the value of the variable is destroyed, just like any other local variable. This is because you added
comps*
to the beginning of your variable declaration, which made the compiler think that the variable was local to
ReadComponents
. Since
components
also exists outside of the function, the computer can still try to access what it thinks to be
components
, but is really some random value from some other program's memory. This is why it dumps random trash at you. The memory you are reading is probably not even of type
char
!
For your convienience, I fixed and commented your code for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
#include <cstring>
class Components {
struct comps{
// char name[50]; <- As he said, character strings are depreciated in C++.
// std::string is better in pretty much every respect.
std::string name;
};
comps* components; //Heh, i just like the asterisk next to the type, myself. It's your preference.
public:
void ReadComponents();
void ReadProducts();
};
void Components::ReadProducts() {
ReadComponents(); //again, it does not actually return a value.
std::cout << "Results: " << components[5].name << std::endl;
}
// This function does not return anything, therefore it should be void.
void Components::ReadComponents() {
/* Below is the C++ style of dynamic memory. You don't have to put
* the type of the variable. If you do, the compiler will treat the
* variable as it was made again, therefore causing it to delete the
* variable after the function is over.
*/
components = new comps [10];
// also, remember to get rid of the allocated memory by using delete after
// you are done. It's what destructors are for.
components[5].name == "The name of the thing, yo.";
}
// The main function.
int main(int argc, char **argv) {
Components components;
components.ReadProducts();
}
|
Hope this helps!