PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

onexit.c and my bad programming style

For some reason the simple program I was working on stopped working. And it happened ever since it decided to ask me for the location of ONEXIT.C after I press F5. Anyone know what that is about? Also it crashes when I try to CListCtrl.Insertitem.

And I have a feeling I have some bad programming techniques. Here is a simple dialog class that I use simply to load a WAV sample and play it using a ListControl. I have no idea if I need to delete the pointers or not. I thought maybe I only delete pointers if I say 'new'. Anyways takes a look and let me know if there is a better way

Code:

// PlayerDlg.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "PlayerDlg.h"
#include <fmod.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CPlayerDlg dialog

FSOUND_SAMPLE *sndarr[30];
FSOUND_SAMPLE *testtemp;


CPlayerDlg::CPlayerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CPlayerDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CPlayerDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}


void CPlayerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPlayerDlg)
DDX_Control(pDX, IDC_LIST1, m_lcSounds);
//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CPlayerDlg, CDialog)
//{{AFX_MSG_MAP(CPlayerDlg)
ON_BN_CLICKED(IDC_TEST, OnPlay)
ON_NOTIFY(NM_CLICK, IDC_LIST1, OnClickList1)
ON_BN_CLICKED(IDC_OPENFILE, OnOpenfile)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()



BOOL CPlayerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CenterWindow(GetDesktopWindow()); // center to the hpc screen

if (!FSOUND_Init(44100, 32, FSOUND_INIT_GLOBALFOCUS))
{
MessageBox((_T("Could not init")));
exit(1);
}

for (int j = 0;j<30;j++)
{
sounds[j] = "";
}

sounds[0] = "bmyname.wav";
sounds[1] = "byessir.wav";

for (int i = 0;i < 2;i++)
{
int x = m_lcSounds.InsertItem(i, sounds[i]);
if (x == -1)
MessageBox(_T("error!"));
TRACE2("Loading sound: %s into sndarr[%d]",sounds[i],i);
char *pSoundName = GetAnsiString(sounds[i]);
sndarr[i] = FSOUND_Sample_Load(FSOUND_FREE,pSoundName,FSOUND_NORMAL,0);
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CPlayerDlg message handlers


void CPlayerDlg::OnPlay()
{
TRACE1 ("Playing sound located at sndarr[%d] \n", soundindex);
FSOUND_PlaySound(FSOUND_FREE,sndarr[soundindex]);
}


void CPlayerDlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
POSITION pos = m_lcSounds.GetFirstSelectedItemPosition();
if (pos == NULL)
TRACE0("No items were selected!\n");
else
{
while (pos)
{
int nItem = m_lcSounds.GetNextSelectedItem(pos);
TRACE1("Item %d was selected!\n", nItem);
soundindex = nItem;
}
}
*pResult = 0;
}

void CPlayerDlg::OnOpenfile()
{
CString message,sPathName,sFileName;
CFileDialog fileDialog(TRUE, NULL, NULL, OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, (_T("All Files (*.*)|*.*|")), NULL);

fileDialog.DoModal();
sFileName = fileDialog.GetFileTitle();
sPathName = fileDialog.GetPathName();
TRACE2("Loaded file: %s \nFiles Path: %s \n",sFileName,sPathName);

char *pFileName = GetAnsiString(sFileName);
TRACE0("Going to PopulateListControl function\n");
PopulateListControl (pFileName);
}

void CPlayerDlg::PopulateListControl(char* fn)
{
CString tempstr;
tempstr = sounds[0];
int ind = 0;
while (tempstr != "")
{
ind++;
tempstr = sounds[ind];
}
CString fn2 = fn;
TRACE2("Inserting word: %s at index %d into listcontrol\n",fn2,ind);
int xx = m_lcSounds.InsertItem(ind, fn2);
TRACE2("Loading sample named %s into array at: sndarr[%d]\n",ind,fn2);
sndarr[ind] = FSOUND_Sample_Load(FSOUND_FREE,fn,FSOUND_NORMAL,0);
}

char* CPlayerDlg::GetAnsiString(const CString &s)
{
int nSize = s.GetLength();
char *pAnsiString = new char[nSize+1];
wcstombs(pAnsiString, s, nSize+1);
return pAnsiString;
}


angedelamort · 22 Jul 2002, 14:26 UTC
And it happened ever since it decided to ask me for the location of ONEXIT.C


To avoid this dialog box, juste create an empty file named onexit.c with nothing in. So, when the debugger ask for it, choose this file. I don't know why the debugger need it, but once he find him, you'll not receive that warning anymore.
UMCP_matt · 22 Jul 2002, 18:32 UTC — ok
but I wonder why is it asking for this file now? And I wonder if it is related to the crashing.

I don't know what to do expect rewrite the app from scratch since I have no idea why all of a sudden the InsertItem function is crashing.
angedelamort · 22 Jul 2002, 19:07 UTC
I don't know why embedded is asking for this file... It always seem to apear randomly... And, if you do nothing... someday it will stop to ask you about this file... and later it will ask again. If anyone know why, It could be interesting to know.

But for your problem, I'm pretty sure there nothing linked with this file.

And for you other problem:
----
sounds[0] = "bmyname.wav";
sounds[1] = "byessir.wav";
----

how is it instanciated?
char sound[25]; //?? I hope not lol

but Be sure to check if the string is correct.
Regarding the DLL searching, you can go into the Project Settings, Debug tab, "Additional DLLs" category, and check the settings for various external files.

Dan East
CString sounds[30];

is from the .h file

I am just going to retype it and hopefully it will not mysteriously stop working..

if anyone is bored I can send them the source and they can play with it



angedelamort wrote:
I don't know why embedded is asking for this file... It always seem to apear randomly... And, if you do nothing... someday it will stop to ask you about this file... and later it will ask again. If anyone know why, It could be interesting to know.

But for your problem, I'm pretty sure there nothing linked with this file.

And for you other problem:
----
sounds[0] = "bmyname.wav";
sounds[1] = "byessir.wav";
----

how is it instanciated?
char sound[25]; //?? I hope not lol

but Be sure to check if the string is correct.
[code][/code]
As I'm looking through your code I'll throw out some comments.

This doesn't affect your problem, but it is standard convention to precede class member variable names with "m_". So your "sounds" variable would be defined as follows:
CString m_sounds[30];

GetAnsiString is allocating memory to store the converted string, which you are not deallocating after the call. That is of course not good, but is not to blame for your current problem.

Your OnClickList1 handler is not necessary. You can retrieve the currently selected CListCtrl items at any time - you need not handle the message and store that in a member variable. Also, you call GetFirstSelectedItemPosition and then iterate positions. It is much easier to iterate all the selected items as follows:
Code:

int idx=m_lcSounds.GetNextItem(-1, LVNI_SELECTED);
while (idx!=-1) {
//Do something with idx
idx=m_lcSounds.GetNextItem(idx, LVNI_SELECTED);
}


Next, you iterate all selected items, yet you are only storing the value of the last selected item. You need not go to the trouble to iterate the all the selected items if you are just going to throw them all out but one. If you do not allow multiple item selection then GetNextItem(-1, LVNI_SELECTED) will suffice to get the currently selected item without a loop.

Thus I would do away with the OnClickList1 function, and rewrite OnPlay as follows to support multiple selected items:
Code:

void CPlayerDlg::OnPlay()
{
int idx=m_lcSounds.GetNextItem(-1, LVNI_SELECTED);
while (idx!=-1) {
TRACE1 ("Playing sound located at sndarr[%d] \n", idx);
FSOUND_PlaySound(FSOUND_FREE,sndarr[idx]);
idx=m_lcSounds.GetNextItem(idx, LVNI_SELECTED);
}

You could very simply add an Update CmdUI handler for the Play button to determine whether or not the Play button should be enabled. It would look something like this:
Code:

void CPlayerDlg::OnUpdatePlay(CCmdUI* pCmdUI) {
pCmdUI->Enable(m_lcSounds.GetNextItem(-1, LVNI_SELECTED)!=-1);
}


Next, the filenames are already stored by the CListCtrl (as the item's name), so you need not keep a duplicate array of CStrings. You can simply CListCtrl::GetItemText to get the filename given the item index. That would be safer in the event that items are inserted in the middle instead of added to the end of the list.

Lines 124-131 in your source code can be replaced with:
int ind = m_lcSounds.GetItemCount();

I think you're making your Unicode / ANSI usage much more difficult than needed. For example, your PopulateListControl takes an ANSI string, which it then has to convert to Unicode to work with. The only time you call that function you have to convert from Unicode to pass the string, so the conversions are totally unnecessary. Generally speaking, you should make all of your strings of type TCHAR, and only convert to make calls to non-Unicode libraries. Thus the only time you should convert to ANSI in your example is before calling FSOUND_Sample_Load.

And to finish up, almost all controls (CListCtrl, CTreeCtrl, etc) allow you to store a DWORD value for each item that you may utilize as you like. For programs like DEXplor, I use that value to store a pointer to some struct that stores needed information about that item. You can also use it to just store a numeric value, such as the handle / index value used by the sound library. Thus you would not need the sndarr array either. The idea is to avoid attempting to maintain arrays that you must synchronize with the position of items in the list control. Not only does it make the code more complex and bug-prone, but it makes removing items from the list extremely difficult. My Play function above would be rewritten as follows to utilize the DWORD user value:
Code:

void CPlayerDlg::OnPlay()
{
int idx=m_lcSounds.GetNextItem(-1, LVNI_SELECTED);
while (idx!=-1) {
TRACE1 ("Playing sound located at %d \n", m_lcSounds.GetItemData(idx));
FSOUND_PlaySound(FSOUND_FREE,m_lcSounds.GetItemData(idx));
idx=m_lcSounds.GetNextItem(idx, LVNI_SELECTED);
}


You would also have to call SetItemData each time you insert an item to set the index as returned by SOUND_Sample_Load. Personally I would load the sample first, then add it to the list. That way you would already know the sample's index, as well as verify that the load suceeded before adding to the list.

Dan East
UMCP_matt · 24 Jul 2002, 22:19 UTC — ..
This doesn't affect your problem, but it is standard convention to precede class member variable names with "m_". So your "sounds" variable would be defined as follows:

Right that is easy to fix. Ill do that

GetAnsiString is allocating memory to store the converted string, which you are not deallocating after the call. That is of course not good, but is not to blame for your current problem.

Ok you mean this line

char *pAnsiString = new char[nSize+1];

when would I delete the pointer? I am not new to pointers I use them but I never really known exactly what I am doing. I guess I could delete it before the return but I cannot do that can I ? Since it returns that character in the pointer?

Your OnClickList1 handler is not necessary. You can retrieve the currently selected CListCtrl items at any time - you need not handle the message and store that in a member variable. Also, you call GetFirstSelectedItemPosition and then iterate positions. It is much easier to iterate all the selected items as follows:

Ok. But it does not seem to hurt to use MFC message maps in this case though I suppose I could just assign a pointer to the control and get info from it anytime I want.

Code:

int idx=m_lcSounds.GetNextItem(-1, LVNI_SELECTED);
while (idx!=-1) {
//Do something with idx
idx=m_lcSounds.GetNextItem(idx, LVNI_SELECTED);
}


Next, you iterate all selected items, yet you are only storing the value of the last selected item. You need not go to the trouble to iterate the all the selected items if you are just going to throw them all out but one. If you do not allow multiple item selection then GetNextItem(-1, LVNI_SELECTED) will suffice to get the currently selected item without a loop.

Yeah that one line does do what my 10 lines do. Ok ill use that


Thus I would do away with the OnClickList1 function, and rewrite OnPlay as follows to support multiple selected items:
Code:

void CPlayerDlg::OnPlay()
{
int idx=m_lcSounds.GetNextItem(-1, LVNI_SELECTED);
while (idx!=-1) {
TRACE1 ("Playing sound located at sndarr[%d] \n", idx);
FSOUND_PlaySound(FSOUND_FREE,sndarr[idx]);
idx=m_lcSounds.GetNextItem(idx, LVNI_SELECTED);
}

You could very simply add an Update CmdUI handler for the Play button to determine whether or not the Play button should be enabled. It would look something like this:
Code:

void CPlayerDlg::OnUpdatePlay(CCmdUI* pCmdUI) {
pCmdUI->Enable(m_lcSounds.GetNextItem(-1, LVNI_SELECTED)!=-1);
}


Next, the filenames are already stored by the CListCtrl (as the item's name), so you need not keep a duplicate array of CStrings. You can simply CListCtrl::GetItemText to get the filename given the item index. That would be safer in the event that items are inserted in the middle instead of added to the end of the list.

Lines 124-131 in your source code can be replaced with:
int ind = m_lcSounds.GetItemCount();

I think you're making your Unicode / ANSI usage much more difficult than needed. For example, your PopulateListControl takes an ANSI string, which it then has to convert to Unicode to work with. The only time you call that function you have to convert from Unicode to pass the string, so the conversions are totally unnecessary. Generally speaking, you should make all of your strings of type TCHAR, and only convert to make calls to non-Unicode libraries. Thus the only time you should convert to ANSI in your example is before calling FSOUND_Sample_Load.

And to finish up, almost all controls (CListCtrl, CTreeCtrl, etc) allow you to store a DWORD value for each item that you may utilize as you like. For programs like DEXplor, I use that value to store a pointer to some struct that stores needed information about that item. You can also use it to just store a numeric value, such as the handle / index value used by the sound library. Thus you would not need the sndarr array either. The idea is to avoid attempting to maintain arrays that you must synchronize with the position of items in the list control. Not only does it make the code more complex and bug-prone, but it makes removing items from the list extremely difficult. My Play function above would be rewritten as follows to utilize the DWORD user value:
Code:

void CPlayerDlg::OnPlay()
{
int idx=m_lcSounds.GetNextItem(-1, LVNI_SELECTED);
while (idx!=-1) {
TRACE1 ("Playing sound located at %d \n", m_lcSounds.GetItemData(idx));
FSOUND_PlaySound(FSOUND_FREE,m_lcSounds.GetItemData(idx));
idx=m_lcSounds.GetNextItem(idx, LVNI_SELECTED);
}


You would also have to call SetItemData each time you insert an item to set the index as returned by SOUND_Sample_Load. Personally I would load the sample first, then add it to the list. That way you would already know the sample's index, as well as verify that the load suceeded before adding to the list.

Dan East
[/quote]
Code:
Code:
UMCP_matt · 24 Jul 2002, 22:30 UTC — that was a most excellent reply ..thanks
I spent another hour with it and cut the size down in half.. Check it out

I think the key to this MFC stuff is being able to write code using the documentation as opposed to everytime I need something having to get a code snippet and then trying to fit it into my program and I end up with doing things the long way

Code:

// hartmanDlg.cpp : implementation file
//

#include "stdafx.h"
#include "hartman.h"
#include "hartmanDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CHartmanDlg dialog

CHartmanDlg::CHartmanDlg(CWnd* pParent /*=NULL*/)
: CDialog(CHartmanDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CHartmanDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CHartmanDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CHartmanDlg)
DDX_Control(pDX, IDC_LIST1, m_lcsounds);
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CHartmanDlg, CDialog)
//{{AFX_MSG_MAP(CHartmanDlg)
ON_BN_CLICKED(IDC_QUIT, OnQuit)
ON_BN_CLICKED(IDC_PLAY, OnPlay)
ON_BN_CLICKED(IDC_OPEN, OnOpen)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CHartmanDlg message handlers

BOOL CHartmanDlg::OnInitDialog()
{
CDialog::OnInitDialog();

SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon

CenterWindow(GetDesktopWindow()); // center to the hpc screen
if (!FSOUND_Init(44100, 32, FSOUND_INIT_GLOBALFOCUS))
{
MessageBox((_T("Could not init")));
exit(1);
}

int x = m_lcsounds.InsertItem(0, (_T("bmyname.wav")));
if (x == -1)
MessageBox(_T("error!"));
return TRUE; // return TRUE unless you set the focus to a control
}



void CHartmanDlg::OnQuit()
{
CDialog::EndDialog(0);
}

void CHartmanDlg::OnPlay()
{
int soundindex = m_lcsounds.GetNextItem(-1, LVNI_SELECTED);
CString xxx = m_lcsounds.GetItemText(soundindex, 0);
char *pSoundName = GetAnsiString(xxx);
FSOUND_SAMPLE *currsound = FSOUND_Sample_Load(FSOUND_FREE,pSoundName,FSOUND_NORMAL,0);

FSOUND_PlaySound(FSOUND_FREE,currsound);
}

void CHartmanDlg::OnOpen()
{
CFileDialog fileDialog(TRUE, NULL, NULL, OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, (_T("All Files (*.*)|*.*|")), NULL);
fileDialog.DoModal();
CString filename = fileDialog.GetFileName();
int numitems = m_lcsounds.GetItemCount();
int xx = m_lcsounds.InsertItem(numitems, filename);
}

char* CHartmanDlg::GetAnsiString(const CString &s)
{
int nSize = s.GetLength();
char *pAnsiString = new char[nSize+1];
wcstombs(pAnsiString, s, nSize+1);
return pAnsiString;
}
That's looking better. I'll throw out some more comments. :)

You need to delete the pointer returned by GetAnsiString after you're done using it. Generally speaking, it is poor programming practice for a function to allocate data that must be cleaned up elsewhere (that is where C++ is so useful, so classes can simply clean up after themselves in the destructor). Usually you are better off passing a buffer into the function, which the function just fills with info.

I would do away with GetAnsiString and dynamic memory allocation in this case. Also, it's important to check return codes. For example, it is possible for a List Control to not have any selected items, even if it is not empty. I added a simple check to make sure an item is selected before you try to get the item's text. You need to check the return code of FSOUND_Sample_Load as well. This version of OnPlay implements some of those suggestions.

Code:

void CHartmanDlg::OnPlay()
{
int soundindex = m_lcsounds.GetNextItem(-1, LVNI_SELECTED);
if (soundindex!=-1) {
CString xxx = m_lcsounds.GetItemText(soundindex, 0);
char ansistr[MAX_PATH];
wcstombs(ansistr, xxx, sizeof(ansistr));
FSOUND_SAMPLE *currsound = FSOUND_Sample_Load(FSOUND_FREE,ansistr,FSOUND_NORMAL,0);

FSOUND_PlaySound(FSOUND_FREE,currsound);
}
}


You also need to check the return code of DoModal, because the user may have canceled the dialog instead of hitting Okay. This implementation of OnOpen checks the return value, as well as doing away with the CString and int vars.

Code:

void CHartmanDlg::OnOpen()
{
CFileDialog fileDialog(TRUE, NULL, NULL, OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, (_T("All Files (*.*)|*.*|")), NULL);
if (fileDialog.DoModal() == IDOK)
m_lcsounds.InsertItem(m_lcsounds.GetItemCount(), fileDialog.m_ofn.lpstrFile);
}


Dan East
UMCPmatt · 25 Jul 2002, 03:11 UTC — pointers still confuse me
passing a buffer? I am currently sending in the address which contains the characters right?

pointers still confuse me.. there are

xx
*x
&x;

but there is only the VALUE and the ADDRESS..

sso there are 3 of one.. and 2 of the other.. I dont get it..

Ill test the other stuff when I get home


You need to delete the pointer returned by GetAnsiString after you're done using it. Generally speaking, it is poor programming practice for a function to allocate data that must be cleaned up elsewhere (that is where C++ is so useful, so classes can simply clean up after themselves in the destructor). Usually you are better off passing a buffer into the function, which the function just fills with info.
Pointers always confuse the hell out of people, and to make matters worse, they're a pain in the arse to explain, as I'm about to prove :) Sorry if this seems patronising, I've just hacked at a piece of text I wrote for somebody else and pasted it here.


The main thing to keep in your head is that there are, as you said, two pieces of information attached to a variable:

a) what the variable contains - the value
b) the address of that variable - the reference


So, say we have a 32-bit long, which is stored in memory at 0x0012, with a value 0x12345678

Code:
unsigned long ul_example = 0x12345678;
// We're pretending that the system allocates space for the variable at 0x0012


Doing this:

Code:
unsigned long *ulp_address = &ul;_example;


Puts the value of 0x0012 into the ul_address pointer variable. The & operator simply gives the reference (i.e. address) of the variable.

Pointer variables, in essence, instead of storing integers, floats, or doubles, store addresses.

So, in the above example, the ulp_address pointer may be allocated at 0x0016, and have a value of 0x0012.

<table>
<tr><td>Address in memory</td><td>Variable</td><td>Content</td></tr>
<tr><td>0x0012</td><td>ul_example</td><td>0x12345678</td></tr>
<tr><td>0x0016</td><td>*ulp_address</td><td>0x0012</td></tr>
</table>

(Hrrm, tables don't work even with the "Disable HTML" off then?)

With pointers, you can also do "pointer arithmetic", which is the same as adding or subtracting the size of the data-type that the pointer is pointing to from the address the pointer points to:

Code:
ul_address = &ul;_example;
ulp_address--; // ulp_address now points at 0x0008
ulp_address+=2;// ulp_address now points at 0x0016


Because the pointer's is just an address, you can also assign it to other pointers:
Code:
char *cp_address;
cp_address=(char *)ulp_address;


In the above, you're using the cast "(char *)" to tell the compiler that you really do know what you're doing, and that you really would like the cp_address pointer to point at the same address as ulp_address.

You can then do things like this:
Code:
char *cp_address=(char *)ul_address;
*cp_address='A'; // 0x0012 = 'a' now
cp_address++; // cp_address=0x0013 now - a char is 1 byte
*cp_address='B'; // 0x0013= 'b' now


When used with a pointer, the * operator de-references it, i.e., it says to write the value on the right of the assignment (the r-value) at the address the pointer is pointing at, rather than as the address the pointer points at.


Now, to your problem. A buffer is a block of memory. When you call malloc() or a similar function (or the new operator), memory is reserved for your use and you're passed a pointer to the memory:

Code:
cp_address=(char*)malloc(1024);
if(cp_address!=0)
{
// everything is ok, we allocated 1KB of memory
}
else
{
// oops - couldn't allocate buffer
}



You can then use that memory as you wish, and tell other functions where it is by passing them a pointer (which is the address of the memory).

Code:
//...
my_func(cp_address);
//...
}

void my_func(char *buffer)
{
*buffer='A'; // set the first byte of the buffer to A
}


When you're finished with the memory, it's your responsibility to get rid of it:

free(cp_address);


.. which tells the system that it can have the memory back.

NB: I'm using malloc() and free() - if you're using C++, you shouldn't use those unless you have to - use the new and delete operators.

Sometimes, it's also the case that a function you call allocates memory on your behalf and passes back a pointer for you to use (and destroy).

In that case, you simply call the function, use the return, and delete the pointer it gives you, using:

Code:
free(cp_address);
// OR
delete cp_address;



For the rest of it, I'm just going to cut-and-paste stuff from MSDN:

The new and delete operators can also be used for built-in types, including arrays. If pointer refers to an array, place empty brackets before pointer:


Code:
int* set = new int[100];
//use set[]
delete [] set;



The following code example allocates a character array and an object of class CName and then frees them.

Code:
#include <string.h>

class CName
{
char m_szFirst[256];
char m_szLast[256];
public:
void SetName(char* pszFirst, char* pszLast)
{
strcpy(m_szFirst, pszFirst);
strcpy(m_szLast, pszLast);
}
};

void main()
{
char* pCharArray = new char[256]; // Allocate memory for the array
strcpy(pCharArray, "Array of characters");
delete [] pCharArray; // Deallocate memory for the array
pCharArray = NULL;

CName* pName = new CName; // Allocate memory for the object
pName->SetName("Firstname", "Lastname");
delete pName; // Deallocate memory for the object
pName = NULL;
}


HTH, cheers,

Ref.
UMCP_matt · 29 Jul 2002, 23:16 UTC — that was great.. I understand it mostly
so tell me if this is right

if I say

int x;

then I can only refer to x as

x (the value)
&x (the address)

but if I say

int *x

I can refer to x as

*x (the value)
&x OR x (the address)

right?

Code:

CHartmanDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
}


Where is m_pMainWnd defined? I can not seem to find it. And what is that 2nd line needed for anyways? I created a About dialog and just commented out that 2nd line and it seemed to work fine.

The reason for using Objects like

Name.First vs. Name->First confuses me still. I understant one is a pointer and one is not. But I am confused on why I pick one over the other.
BurningSheep · 29 Jul 2002, 23:31 UTC

if I say

int *x

I can refer to x as

*x (the value)
&x OR x (the address)

right?


x holds the address where the actual value of the int is stored.
&x holds the value where x is stored... so you can say that &x holds the address to the address to the integer value.
You are probably not going to need to use &x very soon in this manner :)

About the -> or the .
It tells the compiler whether you are accessing a function/member var of a class or a pointer to a class.

MyObj obj;
obj.m_var = 10;

and

MyObj * obj = new MyObj;
obj->m_var = 10;

you only need to remember that
int *i;

i is a pointer to an integer. What does i point to? Nothing, as we have not initialized that variable. There is no integer at that point, thus you cannot say something like *i=123; because i points to undefined memory. If you did the following:
int j;
i=&j;

Then i is a pointer to j. You could of course dynamically allocate some memory as well:

int *i=new int;
or
int *i = malloc(sizeof(int));

The point is that

int *i;

is certainly not a shortcut for

int i;
&i;

Regarding your code excerpt, every MFC application has a class derived from CWinApp which contains the application's entry point. CWinApp is derived from CWinThread - after all, your main instance is just your application's primary thread. CWinThread contains the m_pMainWnd data member.

Dan East
int *i;

i is a pointer to an integer. What does i point to? Nothing, as we have not initialized that variable. There is no integer at that point, thus you cannot say something like *i=123; because i points to undefined memory. If you did the following:
int j;
i=&j;

but could I say

&i;=&j;

???

Then i is a pointer to j. You could of course dynamically allocate some memory as well:

int *i=new int;
or
int *i = malloc(sizeof(int));

ok that makes sense

The point is that

int *i;

is certainly not a shortcut for

int i;
&i;

Regarding your code excerpt, every MFC application has a class derived from CWinApp which contains the application's entry point. CWinApp is derived from CWinThread - after all, your main instance is just your application's primary thread. CWinThread contains the m_pMainWnd data member.


what do I need to include so that my source file SEES m_pMainWnd?


Dan East
[/quote]
&i;=&j; will not even compile. Think of the & operator as "tell me the address of this var". You can't change the address of a variable (don't misunderstand, I'm not talking about changing the value of a variable that is a pointer). The compiler determines what the address is for a variable (it is allocated off of the stack) and you cannot change that value.

Let me delve into this, and hopefully I won't confuse things more. Each running program has a stack, which is a chunk of memory given to the program at startup. The size of this memory is predefined - you set it in the linker settings - it cannot grow or shrink while your application is running. The memory for all variables that are not dynamically allocated comes from the stack. So let's take a look at an example:
Code:

{
short x;
}


When program execution meets the opening bracket, the variable short x comes into scope. So the compiler must come up with a chunk of stack memory to store an short value. So it picks 2 contiguous bytes (the size of an short) of free stack space, and calls that "x". If you do &x;, the result is simply the memory address for the first of the 2 bytes. Now you can't do something like this: &x;=0; because how can we change x's address? The compiler came up with a chunk of stack space to store x's value, and we cann't change where x's value is stored.

Hopefully to make it clearer, here's another example:
Code:

{
short *x;
}


Now when we hit the opening bracket, the compiler needs to come up with storage space for short *x. All pointers are the same size, regardless of what they point to (because a pointer is just a memory address, and all memory addresses are 32 bits on a 32 bit system). So the compiler comes up with 4 bytes of stack space to store a pointer value. So in this case x has an address, just like the previous example. It is &x.; What x points to is just x. The value of what x points to is *x. Does that make sense? If you want a pointer to a pointer, you could do:
Code:

{
short i=123;
short *x;
short **y;
x=&i;
y=&x;

i == *x == **y;
x == &i;
y == &x;
}



I don't quite know what you mean by "seeing m_pMainWnd". Take a look at the MFC header file afxwin.h, line 3921 and you'll see:
Code:

CWnd * m_pMainWnd // main window (usually same AfxGetApp()->m_pMainWnd)


Dan East
UMCP_matt · 30 Jul 2002, 19:34 UTC — ..
So in this case x has an address, just like the previous example. It is &x. What x points to is just x. The value of what x points to is *x.

this is the most important line to understand I think.

int *x;

&x is the address

what is the difference between &x and x
x point to a address
&x is a address.. so they are the same right?

I think I assign a value like

*x = 5;

since *x is the value of what &x (address of x) points to
angedelamort · 30 Jul 2002, 21:30 UTC

int *x;

&x is the address


x here is already a pointer to an address... It point to an address in memory. The & operator give you the address of the address lol.

But here what it trouble you
---- 1 ----
int i = 0;
cout << i << " " << &i;
---- 2 ----
int *i = new int;
*i = 0;
cout << *i << " " << i;
-----------

Yeah, the 2 of them give you an @ in the memory. So, it looks like the same things. But the difference is how it was allocated. The first one is static: for i, it's a memory block and &i point to that block and for the second one (*i), the new return an address of a block that was created by the new. So i point to that block.

I hope you will not be confuse anymore with that :)
UMCP_matt · 30 Jul 2002, 22:44 UTC — i tihnk you got it
i seem to be getting confused cause I forget about how x is intialized..

so when I see

&x I ALWAYS tihnk address of x

but i think this is only the case if x is initialized like

int x;

but if it is intialized like

int *x

THEN x is ALREADY the address so saying &x makes no sense..

am I getting it?

I use pointers all the time I am hoping once I really understand what I am doing everything will make more sense.

so

char *x

x is the address that contains the character

so to assign it a value I say

*x = 'c';

yes?

what if I wanted a string.. I would say

*x = "something";

and

x[3] = 'e';

right?
You're still confused (and wrong) in your assumptions.

int *x;

&x; certainly makes sense. It's taking the address of a pointer variable that points to an int.

In your other case:

char *x;

*x = 'c';

This is horrible as you're storing the character 'c' into an unknown memory address that most certainly doesn't belong to your application. "Oh bartender, another pint of 0xC0000005 Access Violation please..."

The best thing for you to do is to write some simple lines of C code assigning values to various variables and then look at the values in the debugger and the memory watch window when you step through your app until you understand what is happening.
angedelamort · 31 Jul 2002, 03:08 UTC
here a sample of code to see how it works:

Code:

//in C++

//this fct want a pointer to an address
//this will modify the param
void fct_a(int *a)
{
*a = 5;
}

//this fct want an address of a int value
//this will modify the param
void fct_b(int &b)
{
b = 3;
}

//this fct want a int value
//this will not modify the param
void fct_c(int c)
{
c = 1;
}

int main()
{
int val1 = 1;
int val2 = new int(2);

//now let's try to understand how we should call the fct
//for value 1
fct_a(&val1);
fct_b(val1);
fct_c(val1);

//for value 2
fct_a(val2);
fct_b(*val2);
fct_c(*val2);

return 0;
}


This is the simpliest example i could give you to try to understand. Like digby said, write some functions and try to understand why you should use pointer instead of static and vice-versa.

Have Fun

PS. Hope I've not made too much mistake in dis little prog ;)
Another item that is incorrect:

char *x
*x = "something";

This is not correct. In C, arrays behave just like pointers. Think of an array as a pointer to the first item in the array. Now, "something" is just an array of chars. When you work with it, think of it as a pointer (char *) to the first character of the array. So this is correct:

char *x;
x="something";

Since "something" is really just a pointer, and you want to assign it to a pointer (char *x), you just assign it directly.

Here is another example with a different type of variable:

int x[10];
int *px;
px=x; // Not *px=x; nor px=&x; nor *px=&x;


Finally, angedelamort used an example where a function takes a parameter by reference:
void fct_b(int &b;)

First off, that syntax "int &b;" is only valid as a parameter. Thus you cannot declare a variable like this:

int &b;

Second, passing by reference is essentially passing a pointer to the function, but within the function you don't treat the variable like a pointer (this was probably done to make C a little more friendly to newbies, and actually reduces the need for using pointers). Basically what this means is a) changes made to the parameter variable within the function affects the variable that was passed in, and b) function calling is more efficient when passing a struct or class in, because a copy is not made of the variable.

Here's a brief example illustrating the 3 ways of passing a variable to a function:
Code:

void func1(int &x;) {
x++;
}

void func2(int *x) {
(*x)++;
}

void func3(int x) {
x++;
}

int i=0;
// i == 0

func1(i);
// i == 1

func2(&i;);
// i == 2

func3(i);
// i == 2

Note that the call to func3 did not change i's value, because a copy of i was made for use by the function, (since the function did not accept the variable by reference, or a pointer to the variable).

The thing that helps me the most is to take C to a lower level. If you can think of any var, struct, whatever, as raw bytes (like an array of bytes), then it helps a great deal with pointers, arrays, etc (especially when pointer arithmetic comes into play).

Finally, it helps if you precede variables that are pointers with p. So a pointer to an integer would be something like:

int *pNum;

That may help keep you from confusing pointers to real vars.

Dan East
UMCP_matt · 31 Jul 2002, 18:49 UTC — ok ill put it in the debugger
I think that is the best way. I need to straighten out the confusion about assignments and sending parameters..

though I guess when I start using C#.net I wont need to worry bout this.