How to use const pointers in C

5 Answers

0 votes
#include <stdio.h>
 
int main(void)
{
    int n;
    const int *p;
    
    p = &n;  
    *p = 23; // error: assignment of read-only location '*p'
 
    return 0;
}
 
   
/*
run:
     
 
*/

 



answered Jul 27, 2017 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
    int n;
    int *const p = &n; 
    *p = 23;  

    printf("%d", *p);
 
    return 0;
}
 
   
/*
run:
  
23
 
*/

 



answered Jul 27, 2017 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
    int n;
    int *const p = &n; 
    *p = 23;  

    printf("%d", *p);
   
    int x;
    
    p = &x; // error: assignment of read-only variable 'p'
     
    return 0;
}
 
   
/*
run:
  

 
*/

 



answered Jul 27, 2017 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
    int n;
    int *const p = &n; 
    
    *p = 23;  
    printf("%d\n", *p);
   
    *p = 100;
    printf("%d\n", *p);
     
    return 0;
}
 
   
/*
run:
  
23
100
 
*/

 



answered Jul 27, 2017 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
    int n;
    const int* const p = &n;
    
    *p = 23;  // error: assignment of read-only location '*p'

    return 0;
}
 
   
/*
run:
  
23
100
 
*/

 



answered Jul 27, 2017 by avibootz

Related questions

1 answer 172 views
1 answer 156 views
1 answer 129 views
129 views asked Jan 1, 2021 by avibootz
1 answer 185 views
185 views asked Jan 1, 2021 by avibootz
9 answers 596 views
596 views asked Jul 28, 2017 by avibootz
...