By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,775 Members | 1,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,775 IT Pros & Developers. It's quick & easy.

dynamic memory allocating

P: n/a
i'm having a really hard time with this one:

class foo
{
private:
char* p;
public:
foo(int);
};
foo::foo(int j)
{
p = new char[j];
p[0] = '1';
p[1] = '2';
};
int main(void)
{
foo k(2);
return 0;
}
why can't i set the value of p[1]? p[0] passes ok, while p[1] = '2' is just
ignored.
please help
--
You're never too young to have a Vietnam flashback
Apr 24 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Mon, 24 Apr 2006 16:31:17 +0200, "filox"
<fi*****************@yahoo.com> wrote:
i'm having a really hard time with this one:

class foo
{
private:
char* p;
public:
foo(int);
};
foo::foo(int j)
{
p = new char[j];
p[0] = '1';
p[1] = '2';
};
int main(void)
{
foo k(2);
return 0;
}
why can't i set the value of p[1]? p[0] passes ok, while p[1] = '2' is just
ignored.
please help


What do you mean by "ignored"? Are you trying to create a C-style
string? If so, you will need to leave room for the null byte at the
end.

(BTW, you have a memory leak -- by not calling "delete [] p;" in the
destructor of your class or some other appropriate place).

--
Bob Hairgrove
No**********@Home.com
Apr 24 '06 #2

P: n/a
uhm, never mind. there's actually no problem, i just put too much fait in Ms
Visual Studio debugger :)
its ok now. thanks for your effort, though

--
You're never too young to have a Vietnam flashback
"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:5n********************************@4ax.com...
On Mon, 24 Apr 2006 16:31:17 +0200, "filox"
<fi*****************@yahoo.com> wrote:
i'm having a really hard time with this one:

class foo
{
private:
char* p;
public:
foo(int);
};
foo::foo(int j)
{
p = new char[j];
p[0] = '1';
p[1] = '2';
};
int main(void)
{
foo k(2);
return 0;
}
why can't i set the value of p[1]? p[0] passes ok, while p[1] = '2' is justignored.
please help


What do you mean by "ignored"? Are you trying to create a C-style
string? If so, you will need to leave room for the null byte at the
end.

(BTW, you have a memory leak -- by not calling "delete [] p;" in the
destructor of your class or some other appropriate place).

--
Bob Hairgrove
No**********@Home.com

Apr 24 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.