Does this...
char* myString = "hello";
... have the same effect as this?
char actualString[] = "hello"; char* myString = actualString;
It depends upon different issues like Operating system, CPU architecture etc. Usually it depends upon the word size of underlying processor for example for a 32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer size can be 8 bytes. So for a specific architecture pointer size will be fixed.
initialize all pointers to zero. if you cannot guarantee a pointer is valid, check that it is non-0 before indirecting it. when deleting objects, set the pointer to 0 after deletion. be careful of object ownership issues when passing pointers to other functions.
No.
char str1[] = "Hello world!"; //char-array on the stack; string can be changed char* str2 = "Hello world!"; //char-array in the data-segment; it's READ-ONLY
The first example creates an array of size 13*sizeof(char)
on the stack and copies the string "Hello world!"
into it.
The second example creates a char*
on the stack and points it to a location in the data-segment of the executable, which contains the string "Hello world!"
. This second string is READ-ONLY.
str1[1] = 'u'; //Valid str2[1] = 'u'; //Invalid - MAY crash program!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With