C pointer constant and constant pointer

Source: Internet
Author: User

Two ways to declare constants in C language

const   INT   valueint   const   Value

If you want to declare a constant pointer, which is a pointer to a constant, you can refer to the constant declaration above to modify

const   INT   *ptrint   const   *PTR

Consider *ptr as a whole, then ptr in *ptr is a pointer to a constant. As the name implies, a pointer to a constant, then it is not possible to modify this value by this pointer.

#include <stdio.h>int main () {int val = 123;int Const *PTR = &val;*ptr = 111;return 0;} Error: Error:read-only variable is not assignable        *ptr = 111;        ~ ~ ~ ^1 Error generated.

However, you can still modify the value of this amount in other ways. For example

#include <stdio.h>int main () {int val = 123;int Const *PTR = &val;val = 222;printf ("%d\n", *ptr); return 0;} Output: 222

The meaning of a constant pointer is that you cannot modify the value it points to by using this pointer.

Pointer constants

It can be understood that a constant is defined first, and that the constant is a pointer type.

int val = 123;int * Const PTR = & val;

PTR is just a constant, and its value is a fixed memory address.

#include <stdio.h>int main () {char *message = "Hello, world\n";//Here PTR is the memory address of "hello,world\n" char * const PTR = Messag e;printf ("%s\n", ptr);//Even if you modify the value of the message and do not modify the PTR value, PTR still points to "Hello, world\n" message = "Hello, maomao\n";p rintf ("%s\n", PTR); return 0;} Output Hello, Worldhello, world

Constant pointer to constant

Char Const  *  const PTR;

The pointer is a constant, and you cannot modify the value pointed to by the pointer.

C pointer constant and constant pointer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.