Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do these statements about pointers have the same effect?

Tags:

Does this...

char* myString = "hello"; 

... have the same effect as this?

char actualString[] = "hello"; char* myString = actualString; 
like image 573
Pieter Avatar asked Jan 19 '10 19:01

Pieter


People also ask

Are all pointers the same size?

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.

What is valid about pointer?

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.


1 Answers

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! 
like image 119
BlueRaja - Danny Pflughoeft Avatar answered Nov 09 '22 06:11

BlueRaja - Danny Pflughoeft