RE: [Dev-C++] Structures and Arrays and Pointers, Oh My!
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <iv...@at...> - 2003-05-09 14:25:15
|
-----Original Message-----
From: dev...@li...
[mailto:dev...@li...] On Behalf Of David =
McKen
Sent: Friday, May 09, 2003 5:52 AM
To: dev...@li...
Subject: [Dev-C++] Structures and Arrays and Pointers, Oh My!
Ok, I am having trouble using the above 3 together.
=20
Slay_msg is a array of pointers to characters (strings)
struct pc_data {
char * slay_msg[3];
}
=20
//a pointer to pc_data is a member of the char_data struct.
struct char_data {
...
pc_data * pcdata;
}
=20
//A pointer is declared of type char_data and initalized to the required
values.
char_data * ch =3D new char_data; //Assume everything has been =
initalized.
=20
Since you use operator new, it is a C++ program. In C you have to use =
the
malloc() family.
=20
=20
My question is: How do I access the strings in the array slay_msg?
=20
ch->pcdata->slay_msg[<index here>];=20
=20
C90:
=20
unsigned long i;
=20
char_data *ch=3Dmalloc(sizeof(*ch));
=20
if(!ch)
{
/* Error handling code */
}
=20
=20
ch->pcdata=3Dmalloc(sizeof(*(ch->pcdata));
=20
if(!(ch->pcdata))
{
/* Error handling code */
}
=20
=20
for(i=3D0; i<3; ++i)
{
ch->pcdata->slay_msg[i]=3Dmalloc(WHATEVER_SIZE_OF_CHARACTERS);
=20
if(ch->pcdata->slay_msg[i]=3D=3DNULL)
{
/* Error handling code */
}
}
=20
=20
=20
This low level stuff in C++98:
=20
#include <new>
=20
=20
// This try block in reality is usually applied in the function call, =
not in
the definition
// but i place it here to demonstrate the whole error handling =
mechanism.
=20
try
{
=20
char_data *ch=3Dnew char_data;
=20
ch->pcdata=3Dnew pc_data;
=20
=20
for(unsigned long i=3D0; i<3; ++i)
ch->pcdata->slay_msg[i]=3Dnew char[WHATEVER_SIZE_OF_CHARACTERS];
}
=20
catch(std::bad_alloc)
{
// Error handling code
}
=20
=20
=20
Ioannis Vranos
* Programming pages: <http://www.noicys.freeurl.com/>
http://www.noicys.freeurl.com
* Alternative URL 1: <http://run.to/noicys> http://run.to/noicys
* Alternative URL 2: <http://www.noicys.cjb.net/> =
http://www.noicys.cjb.net
|