M
mehafi
Hi,
Why this program work?
#include<iostream.h>
class test
{
public:
char *ptr;
void setPtr(char* p){
ptr = p;
}
void print(){
cout << ptr << endl;
}
};
main()
{
test t;
t.setPtr("abc");
t.print();
system("pause");
}
Is argument of function setPtr - "abc" - a temporary char table, made
on stack, which is deleted when setPtr function ends? If it is, the
pointer - ptr - point then to the memory addres which was deleted, so
print method should print random characters or may crash the program.
When I made char table using new:
main()
{
char* tab = new char[4];
strcpy(tab, "abc");
test t;
t.setPtr(tab);
delete[] tab;
t.print();
system("pause");
}
print() method prints random characters.
But why the first program doesn't crash / prints random chars ?
thanks in advance
best regards
mehafi
Why this program work?
#include<iostream.h>
class test
{
public:
char *ptr;
void setPtr(char* p){
ptr = p;
}
void print(){
cout << ptr << endl;
}
};
main()
{
test t;
t.setPtr("abc");
t.print();
system("pause");
}
Is argument of function setPtr - "abc" - a temporary char table, made
on stack, which is deleted when setPtr function ends? If it is, the
pointer - ptr - point then to the memory addres which was deleted, so
print method should print random characters or may crash the program.
When I made char table using new:
main()
{
char* tab = new char[4];
strcpy(tab, "abc");
test t;
t.setPtr(tab);
delete[] tab;
t.print();
system("pause");
}
print() method prints random characters.
But why the first program doesn't crash / prints random chars ?
thanks in advance
best regards
mehafi