int *pia=newint[ivec.size()];
int *tp=pia;
tp[0]=0;
tp[1]=1;
delete [] pia;
this is a part of an example from a book. after deleting pia, it will no longer be safe to use pia such as cout<<pia[0]; , but what about tp? such as cout<<tp[1];.
if using tp is also not safe, why did the author define tp? why didnt he use pia instead of tp?
String literals (stuff in quotes) are treated as char arrays. You can think of the string literal itself as actually having memory reserved for it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
constchar* st = "ssd";
// "ssd" is a char array automatically put in memory somewhere by the compiler
// st now points to that memory
st = "asd";
// "asd" is another char array somewhere else in memory.
// note this doesn't change "ssd"'s memory -- what we're doing here
// is making st point to a different block of memory. One that contains
// a different string.
cout << st;
// since 'st' points to the automatically generated char array "asd"
// this prints "asd"
EDIT: strictly speaking, string literals are treated as const char arrays. Blah blah.
i got it! st = "asd";means st points to another memory, im not changing the stuff that st points to. if i go like this : constchar * const st="ssd"; i can no longer let st = "asd"; make sense.
during working on that problem.. another problem came up..
i tried this:
1 2
char *st="ssd";
cout << st[2];
it will print out 'd'.
then i tried this:
1 2 3
char *st="ssd";
st[2]='s';
cout << st;
i was hoping that it would print out "sss". and then it had nothing wrong during compiling.
but when i ran it, something was wrong and my program was forced to close... why? can you plz try it?
Compilers should error on this (but most don't). I think C lets you get away with this, but in C++ it's not kosher.
The problem here is that "ssd" is a constant string literal. The compiler will automatically put that literal in memory, but that memory cannot be modified.
IE: 'st' should be a constchar* because it's pointing to const chars.
Instead, if you want to do this, you should explicitly put the string in your own space in memory:
1 2 3 4 5 6 7 8
char buffer[] = "ssd"; // puts "ssd" in memory
char* st = buffer; // now 'st' points to that memory
st[2] = 's'; // now this works
cout << st; // this prints "sss"
cout << buffer; // this also prints "sss"
so in my codes, st[2] = 's'; means im trying to modify a constant string liberal ??
i got it ! thank you so much, by the way, im looking forward to your book.