Re: Help-a-Dummy Please
- From: "Vladimir Grigoriev" <vlad.moscow@xxxxxxx>
- Date: Thu, 4 Sep 2008 20:24:45 +0400
"PvdG42" <pvdg@xxxxxxxxxxxxx> wrote in message
news:OEtW0GpDJHA.524@xxxxxxxxxxxxxxxxxxxxxxx
I received this from a former student who obviously thinks I know more than
I do. It's a three file standard C++ Win32 console app, designed to be put
in an empty project in VS 2008 Pro. The code is short, so I'm pasting all 3
files' content here.
Observations: Compiles with warnings about undimensioned arrays, but
appears to run OK if built in Release Mode. In Debug Mode it crashes while
exiting:
"Debug error Check Failure #2, stack around Switches is corrupt".
Any observations very much appreciated.
File switches.h
#ifndef SWITCHES
#define SWITCHES
class switches
{
public:
switches(int new_numArgs, char* new_Args[]);
~switches();
void showSwitches();
private:
int numArgs;
char * Args[];
};
Well, when you define an object of this class the compiler must know how
much memory it must allocate for the object.
As the memory for the array char * Args[] is allocated outside the object as
we see from the constructor this class member should be defined as
char **Args;
#endif
File switches.cpp
#include <iostream>
#include "switches.h"
using std::cout;
using std::endl;
switches::switches(int new_numArgs, char * new_Args[])
{
numArgs = new_numArgs;
*Args = *new_Args;
}
C/C++ does not pass arrays as arguments to functions. It passes only a
pointer of the same type as an array which points to the first element of
that array. So when you write
switches::switches(int new_numArgs, char * new_Args[])
C/C++ passes as argument char **.
Moreover Args as it is declared by you in fact is a const pointer to char
**, so it may not be changed.
Thus taking into account that Args should be declared as char **Args the
assignment statement should look as
Args = new_Args;
switches::~switches()
{
}
void switches::showSwitches()
{
for(int i = 0; i < numArgs; i++)
cout << "argv[" << i << "] = " << Args[i] << endl;
}
File main.cpp
#include <iostream>
#include "switches.h"
using std::cout;
using std::cin;
using std::endl;
int main (int argc, char* argv[])
{
switches Switches(argc, argv);
Switches.showSwitches();
for(int i = 0; i < argc; i++)
cout << "argv[" << i << "] = " << argv[i] << endl;
return 0;
}
Vladimir Grigoriev
.
- References:
- Help-a-Dummy Please
- From: PvdG42
- Help-a-Dummy Please
- Prev by Date: Re: Help-a-Dummy Please
- Next by Date: ofstream and locales: how do they use heap memory?
- Previous by thread: Re: Help-a-Dummy Please
- Next by thread: Re: Help-a-Dummy Please
- Index(es):
Relevant Pages
|