code_junkie

How to put values to const char **

Nov 13th, 2011
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. yourfunc(const char **p);
  2. ...
  3. const char *array_str[10];
  4. array_str[0] = "foo"; /* OK, literal is a const char[] */
  5. yourfunc(array_str);
  6.  
  7. cdecl> explain const char **table
  8. declare table as pointer to pointer to const char
  9. cdecl> explain const char * const *table
  10. declare table as pointer to const pointer to const char
  11. cdecl> explain const char * const * const table
  12. declare table as const pointer to const pointer to const char
  13.  
  14. #include <iostream>
  15. using namespace std;
  16.  
  17. void print3( const char **three ) {
  18. for ( int x = 0; x < 3; ++ x ) {
  19. cerr << three[x];
  20. }
  21. }
  22.  
  23. int main() {
  24. // "three" holds pointers to chars that can't be changed
  25. const char **three = (const char**) malloc( sizeof( char** ) * 3 );
  26. char a[5], b[5], c[5]; // strings on the stack can be changed
  27. strcpy( a, "abc" ); // copy const string into non-const string
  28. strcpy( b, "def" );
  29. strcpy( c, "efg" );
  30. three[0] = a; // ok: we won't change a through three
  31. three[1] = b; // and the (char*) to (const char*) conversion
  32. three[2] = c; // is just one level deep
  33. print3( three ); // print3 gets the type it wants
  34. cerr << endl;
  35. return 0;
  36. }
  37.  
  38. void printstring( const char **s ) {
  39. printf( "%sn", *s );
  40. }
  41.  
  42. int main( int argc, char** argv ) {
  43.  
  44. char *x = "foo"; // here you have a regular mutable string
  45.  
  46. const char *x2 = x; // you can convert that to a constant string
  47.  
  48. const char **y = &x2; // you can assign the address of the const char *
  49.  
  50. printstring(y);
  51.  
  52.  
  53. }
  54.  
  55. void do_something(const char* s)
  56. {
  57. char* p=(char*)s;
  58. p[0]='A';
  59. }
  60.  
  61. const char **foo = ...;
  62. **foo = 'a'; // not legal
  63.  
  64. // all the following is legal
  65. const char **foo = 0;
  66.  
  67. foo = (const char **)calloc(10, sizeof(const char *));
  68.  
  69. foo[0] = strdup("foo");
  70. foo[1] = strdup("baz");
  71.  
  72. char **foo = ...;
  73. func((const char **)foo);
Add Comment
Please, Sign In to add comment