Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to use const pointer in C

1 Answer

0 votes
#include <stdio.h>

int main() {
    int n = 20;
    const int *p1 = &n;
    printf("a. %d %d\n", n, *p1);
    n = 900;
    // *p = 800; // error: assignment of read-only variable ‘p1’
    printf("b. %d %d\n", n, *p1);
 
    int x = 50;
    p1 = &x;
    printf("c. %d %d %d\n", n, *p1, x);
    
    n = 1000;    
    int * const p2 = &n;
    printf("d. %d %d\n", n, *p2);
    // p2 = &x; // error: assignment of read-only variable ‘p2’
    *p2 = 17;
    printf("e. %d %d\n", n, *p2);

    return 0;
}
 


/*
run:
 
a. 20 20
b. 900 900
c. 900 50 50
d. 1000 1000
e. 17 17
 
*/

 



answered Jan 1, 2021 by avibootz
edited Jan 1, 2021 by avibootz

Related questions

9 answers 534 views
534 views asked Jul 28, 2017 by avibootz
1 answer 104 views
1 answer 103 views
1 answer 113 views
1 answer 113 views
1 answer 116 views
116 views asked May 13, 2021 by avibootz
1 answer 151 views
...