dynamic memory allocating

F

filox

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
 
B

Bob Hairgrove

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).
 
F

filox

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 said:
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top