简体   繁体   中英

assigning address of a const variable to non const pointer

I have a question

const int a=10;
int *ptr;
ptr = (int *)&a;

What is the use of (int *) in the third line above.

Just like the above if we have

char str[]="abc";
char *pc;
pc = str;

is the above assignment right and if it is then why is not in the first case.

Without that cast you'll get a compiler warning. &a is a const int * not a int *.

"const int a" is a constant integer. It cannot be modified. If you try to assign to it, the compiler won't let you. If you successfully play tricks to get around the compiler, your program might crash or worse.

"int* ptr" is a pointer to non-constant integers. If you write an assignment "*ptr = 100;" the compiler will allow it without any problems. If ptr is a null pointer or undefined, this will crash or worse. If ptr points to non-constant integer, it will assign 100 to that integer. If ptr points to a constant integer, it will crash or worse.

Because of that, the compiler doesn't allow you to assign the address of a to p. Because it is asking for trouble.

Now the assignment "ptr = (int *)&a;". &a is the address of a. a is a constant integer, &a is a pointer to a constant integer. (int *) is a cast . You tell the compiler to convert &a to a "pointer to int". Because it is a pointer to int, not pointer to const int, you can assign this to ptr. But the thing that ptr points to is still a and it is still constant.

If you read *ptr, this will work just fine. Reading *ptr will give the number 10. Writing to *ptr, like *ptr = 100, will crash or worse. Basically, by using the cast you told the compiler "shut up, I know what I'm doing". You better do.

--> const int i = 10;

i is stored in read only area.(basically to tell compiler that this value cannot be changed )

i is of type "const int" , and &i is of type "const int *" .

So type casting is need.

int *ptr = (int *)&i; to match it

You can avoid it by declaring as below

`int const *ptr = &i;`        

p is of type "const int" , types are matching no issue

----------updated for your query-------

Pointer to constant can be declared in following two ways.

1) const int *ptr; or int const *ptr; both are same.

But not this ---> 2) int *const ptr; is same as 1st ,this is Constant pointer to variable.

in case 1)We can change pointer to point to any other integer variable , but cannot change value of object (entity) pointed using pointer ptr.

in case 2)we can change value of object pointed by pointer, but cannot change the pointer to point another variable .

你需要强制转换,因为你忘了将ptr声明为指向常量int的指针:

int const *ptr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM