C language constants and pointers

Source: Internet
Author: User

The C language is powerful and rich in functionality, and also manifested in the combination of const and pointer. It provides different protection for different problems. What is particularly useful is the pointer to a constant.

Link: http://www.cnblogs.com/archimedes/p/c-const-point.html.

Pointer to a constant

You can point the pointer to a constant, which means that the value referenced by the pointer cannot be modified.

Int num = 5; const int limit = 500; int * pi; const int * pci; pi = & num; // point to integer pci = & limit; // point to integer constant

The following code prints the addresses and values of these variables:

# Include <stdio. h> int main (void) {int num = 5; const int limit = 500; int * pi; const int * pci; pi = & num; // point to integer pci = & limit; // point to the integer constant printf ("num-Address: % p value: % d \ n", & num, num ); printf ("limit-Address: % p value: % d \ n", & limit, limit); printf ("pi-Address: % p value: % p \ n ", & pi, pi); printf ("pci-Address: % p value: % p \ n", & pci, pci); return 0 ;}

The pointer pointing to a constant cannot be resolved and the value referenced by the pointer cannot be changed. However, the pointer value is not a constant and can be changed. The pointer can be changed to another integer constant or a common integer.

Declaring pci as a pointer to an integer constant means:

  • Pci can be changed to point to different Integer constants.

  • Pci can be changed to point to different non-Integer constants.

  • You can describe pci to read data.

  • You cannot describe pci to modify the data it points.

Note: The data type and the order of const are irrelevant and can be exchanged.

Const int * pci = int const * pci

Constant pointer to a very large number

The pointer is immutable, but the data it points to is variable.

int num;int *const cpi = &num;

If you initialize cpi to point to the constant limit, an error will occur because the data indicated by cpi can be modified, but the constant cannot be modified.

const int limit = 500;int * const cpi = &limit;
Constant pointer to a constant

This type of pointer is rarely used. This type of pointer cannot be modified, and the data it points to cannot be modified. The following is an example:

const int * const cpci = &limit;

Not always assign the constant address to cpci, as shown below:

int num;const int * const cpci = &num;

Initialization is required when declaring such pointers.

Pointer to "constant pointer to constant"
#include <stdio.h>int main(void){        const int limit = 500;    const int * const cpci = &limit;    const int * const * pcpci = &cpci;    printf("%d\n", *cpci);    printf("%d\n", **pcpci);    return 0;}

The following table summarizes the four pointers discussed:

Pointer type Whether the pointer can be modified Whether the data pointing to the pointer can be modified
Pointer to a very large volume Yes Yes
Pointer to a constant Yes No
Constant pointer to a very large number No Yes
Constant pointer to a constant No No
Example

In the following example, the function returns a pointer to a struct constant, which means that the value in the struct is read-only and the qualifier is useful because it tells us some unfeasible operations.

#include<stdio.h>#include<stdlib.h>struct a{    int x;};const struct a * function(void){    struct a *ptr;    if((ptr = (struct a *)malloc(sizeof(struct a))) == NULL)        exit(1);    ptr->x = 0;    return ptr;}int main(void){        int y;    const struct a *ptr;    ptr = function();    y = ptr->x;    return 0;}

If we try to modify it, we will get a gcc error.

int main(void){        int y;    const struct a *ptr;    ptr = function();    ptr->x = 1;    return 0;}

Error: assignment of read-only location '* ptr'
If you assign a value to a non-struct constant, we will receive a gcc warning.

int main(void){        int y;    struct a *ptr;    ptr = function();    ptr->x = 1;    return 0;}

Warning: assignment discards qualifiers from pointer target type

If type conversion is used, the task runs successfully.

int main(void){    struct a *ptr;    ptr = (struct a *) function();    ptr->x = 1;    return 0;}

Struct constant pointer as a parameter

#include<stdio.h>#include<stdlib.h>struct a{    int x;};struct b{    const struct a *nested_ptr;};const struct a * function(void){    struct a *ptr;    if((ptr = (struct a *) malloc(sizeof(struct a))) == NULL){        exit(1);    }    ptr->x = 0;    return ptr;}void do_something(const struct b *ptr){    const struct a *x = ptr->nested_ptr;}int main(void){    struct b b_obj;    b_obj.nested_ptr = function();    do_something(&b_obj);    return 0;}

Constant pointer

If a pointer is specified as a constant, the const keyword is placed behind "*", just as the prototype of do_something () above can be rewritten to the following form, and none of them can be modified, the ptr variable cannot be modified after it is initialized by calling and passing parameters.

void do_something(const struct b * const ptr);

Constant initialization Extension

A struct constant can be initialized as follows:

int main(void){    const struct a obj = [ 5 ];    return obj.x;}

A pointer to a struct constant can be initialized as follows:

int main(void){    const struct a obj = [ 5 ];    const struct a *ptr_a = &obj;    const struct a *ptr_b = function();    return ptr_a->x;}

Returns a constant pointer.

const struct a * const function(void);

Pass pointer pointing to constant pointer

A common reason for passing a double pointer is to modify the pointer value. See the following example:

void fill_in(const struct a **location){    *location = function();}int main(void){    const struct a *ptr;    fill_in(&ptr);    return 0;}

Let's look at the following code and add const before location.

void fill_in(const struct a ** const location){    *location = function();}

Explanation:

1. the struct is a constant and cannot be modified.

2. pointer to the struct, pointing through location. * location is not a constant and can be modified.

3. The variable location is a constant, meaning it cannot be modified.

You can also add a const:

void fill_in(const struct a * const * const location){    *location = function();}

Error: assignment of read-only location '* location' (because * location is also a constant, gcc error is returned)

The code below is not the content of the Operation struct, nor a pointer to the struct, but allows the function to operate its own local variables through passing parameters.

void make_use_of(const struct a * const *location){    const struct a * const ptr_a = *location;    const struct a *ptr_b = *location;    ptr_b = NULL;    location = NULL;}

Explanation:

1. the struct is a constant and cannot be modified.

2. pointer to the struct, pointing through location. * location is also a constant and cannot be modified.

3. The variable location is non-constant, meaning it can be modified.

4. The local variable ptr_a is a constant and cannot be modified.

4. The local variable ptr_a is not a constant and can be modified.

References

Wikipedia

C and pointer

 

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.