Skip to content

Instantly share code, notes, and snippets.

@benpop
Last active May 2, 2023 14:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benpop/5880243 to your computer and use it in GitHub Desktop.
Save benpop/5880243 to your computer and use it in GitHub Desktop.
Illustrate the difference between char *, char [], char *[], etc., in C.
#include <stdio.h>
#include <string.h>
/* z is format specifier for size_t, the return type of sizeof */
#define SIZEFMT "\t%zu\t%s\n"
/* sizeof gives the memory compiler allocates for x.
# is the stringify operator in the C preprocessor.
for example, #token -> "token". */
#define printsize(x) printf(SIZEFMT, sizeof(x), #x)
#define printlenstr(s) printf(SIZEFMT, strlen(s), (s))
#define printline() printf("\n")
int main(void)
{
/* with array/string literals at initialization,
the sizes are technically unnecessary
-- they're given for illustrative purposes */
char *ap[5] = {"alpha", "beta", "gamma", "delta", "epsilon"};
char aa[3][4] = {"foo", "bar", "baz"};
char **pp = &ap[0];
char (*pa)[4] = &aa[0];
char a[] = "hello, world";
char *p = "hello";
int i, size;
printsize(char); /* according to the C standard this is always 1 */
printline();
printsize(char *); /* size of char pointer --> 4 on 32-bit machine,
8 on 64-bit machine */
printsize(p); /* == sizeof(char *) */
printlenstr(p);
printline();
printsize(char [13]);
printsize(a); /* == (strlen(a) + 1) * sizeof(char) -- +1 for ending '\0'. */
printlenstr(a);
printline();
printsize(char [3][4]);
printsize(aa); /* == 3 * 4 * sizeof(char) */
size = (int)(sizeof(aa) / sizeof(aa[0]));
for (i = 0; i < size; i++)
printlenstr(aa[i]);
printline();
printsize(char (*)[3]);
printsize(pa); /* == sizeof(char (*)[N]) == sizeof(char **) */
for (i = 0; i < 3; i++)
printlenstr(pa[i]);
printline();
printsize(char *[5]);
printsize(ap); /* == sizeof(char *) * 5 */
size = (int)(sizeof(ap) / sizeof(ap[0]));
for (i = 0; i < size; i++)
printlenstr(ap[i]);
printline();
printsize(char **);
printsize(pp); /* == sizeof(char **) */
for (i = 0; i < 5; i++)
printlenstr(pp[i]);
printline();
return 0;
}
@SaraHan774
Copy link

Nice illustration ! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment