code_junkie

Why can't I convert 'char**' to a 'const char* const*' in C?

Nov 10th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. char **a;
  2. const char** b = a;
  3.  
  4. char **a;
  5. const char* const* b = a;
  6.  
  7. void f(const char* const* in) {
  8. // Only reads the data from in, does not write to it
  9. }
  10.  
  11. void foo(const int*);
  12.  
  13. char *y;
  14.  
  15. char **a = &y; // a points to y
  16. const char **b = a; // now b also points to y
  17.  
  18. // const protection has been violated, because:
  19.  
  20. const char x = 42; // x must never be modified
  21. *b = &x; // the type of *b is const char *, so set it
  22. // with &x which is const char* ..
  23. // .. so y is set to &x... oops;
  24. *y = 43; // y == &x... so attempting to modify const
  25. // variable. oops! undefined behavior!
  26. cout << x << endl;
  27.  
  28. char **a;
  29. const char* const* b = a;
  30.  
  31. const char **a;
  32. const char* const* b = a;
  33.  
  34. char **a;
  35. const char* const* b = (const char **)a;
  36.  
  37. #include <stdlib.h>
  38. #include <stdio.h>
  39. void foo(const char * const * bar)
  40. {
  41. printf("bar %s nulln", bar ? "is not" : "is");
  42. }
  43.  
  44. int main(int argc, char **argv)
  45. {
  46. char **x = NULL;
  47. const char* const*y = x;
  48. foo(x);
  49. foo(y);
  50. return 0;
  51. }
  52.  
  53. test.c(8) : warning C4100: 'argv' : unreferenced formal parameter
  54. test.c(8) : warning C4100: 'argc' : unreferenced formal parameter
  55.  
  56. test.c(8) : warning C4100: 'argv' : unreferenced formal parameter
  57. test.c(8) : warning C4100: 'argc' : unreferenced formal parameter
  58.  
  59. test2.c: In function `main':
  60. test2.c:11: warning: initialization from incompatible pointer type
  61. test2.c:12: warning: passing arg 1 of `foo' from incompatible pointer type
  62.  
  63. char c = 'c';
  64. char *p = &c;
  65. char **a = &p;
  66.  
  67. const char *bi = *a;
  68. const char * const * b = &bi;
  69.  
  70. const volatile int *const serial_port = SERIAL_PORT;
  71.  
  72. char *const p = (char *) 0xb000;
  73. //error: p = (char *) 0xc000;
  74. char **q = (char **)&p;
  75. *q = (char *)0xc000; // p is now 0xc000
  76.  
  77. void foo (const char* const& x);
Add Comment
Please, Sign In to add comment