Skip to content

Instantly share code, notes, and snippets.

@h1mesuke
Created July 27, 2010 14:26
Show Gist options
  • Save h1mesuke/492288 to your computer and use it in GitHub Desktop.
Save h1mesuke/492288 to your computer and use it in GitHub Desktop.
C - ポインタ変数に対するconst宣言2
#include <stdio.h>
int main(int argc, const char *argv[])
{
const char *p[] = { "foo", "bar", "baz" };
char * const q[] = { "foo", "bar", "baz" };
const char * const r[] = { "foo", "bar", "baz" };
/**** const type *var ****/
puts("");
printf("p = { \"%s\", \"%s\", \"%s\" }\n", p[0], p[1], p[2]);
/* error */
/* p[0][0] = '\0'; */
/* allowed */
p[0] = "hoge";
printf("p = { \"%s\", \"%s\", \"%s\" }\n", p[0], p[1], p[2]);
/**** type * const var ****/
puts("");
printf("q = { \"%s\", \"%s\", \"%s\" }\n", q[0], q[1], q[2]);
/* allowed but segv */
/* q[0][0] = '\0'; */
/* error */
/* q[0] = "hoge"; */
/**** const type * const var ****/
puts("");
printf("r = { \"%s\", \"%s\", \"%s\" }\n", r[0], r[1], r[2]);
/* error */
/* r[0][0] = '\0'; */
/* error */
/* r[0] = "hoge"; */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment