![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
[solved]Simple problem with C++ dynamic memory allocation: please help.
OK, after hours of debugging my program, I have finally found out where the problem lies. So you don't have to read through my whole program I will offer a simplified case that produces the same error. Please tell me why this error occurs and what I can do to stop it.
//main.cpp
#include "FooClass.h"
main()
{
int i=30;
FooClass* pFoo;
pFoo=(FooClass*)malloc(sizeof(FooClass)*i);
pFoo[0].fooString="Foobar Quux";
}//FooClass.h
#pragma once
#include <string>
using namespace std;
class FooClass
{
public:
string fooString;
};This compiles fine, however it spits out errors when I try to run it. What is the problem? Last edited by uman; Feb 5th, 2005 at 4:10 PM. Reason: Added [solved] to title |
|
|
|
|
|
#2 |
|
Newbie
Join Date: Jan 2005
Posts: 20
Rep Power: 0
![]() |
main()
{
int i=30;
FooClass* pFoo;
pFoo = new FooClass [i];
pFoo[0].fooString="Foobar Quux";
delete[] pFoo;
return 0;
}Last edited by Monster; Feb 5th, 2005 at 4:05 PM. |
|
|
|
|
|
#3 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
Yes, I know about vectors and use them whenever I can, however for what I am doing in my larger program I need arrays.
Thanks anyway for the help though. |
|
|
|
|
|
#4 |
|
Newbie
Join Date: Jan 2005
Posts: 20
Rep Power: 0
![]() |
You beat me... just changed it to an array.
|
|
|
|
|
|
#5 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
Ah, ok I understand now. Thanks a million for the help.
|
|
|
|
|
|
#6 |
|
Newbie
Join Date: Jan 2005
Posts: 20
Rep Power: 0
![]() |
Another example. In the first example you create an array with 30 FooClass objects. In this example you create an array with 30 pointers to FooClass objects. To add a FooClass, you need to allocate space for the class first.
main()
{
int i=30;
FooClass** pFoo;
pFoo = new FooClass *[i]; // create array with 30 pointers
pFoo[0] = new FooClass(); // create a new FooClass
pFoo[0]->fooString="Foobar Quux";
delete pFoo[0]; // delete the FooClass
delete[] pFoo; // delete the array
return 0;
} |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|