// strings is a 2D array (each string is 11 bytes long)
char strings[][11] = {"0123456789", "2222244444", "3333366666"};
printf("String 3 Character 2 is %c\n", strings[2][1]);
How can I code this print statement using pointer arithmetic instead of the strings[2][1]
?
In C, a[b]
is the same as *(a+b)
(and since addition is commutative, that implies that it's also equivalent to b[a]
. People writing for the International Obfuscated C Code Contest frequently rely on this, using things like x["string"];
. Needless to say, it's best to avoid that sort of thing unless you're intentionally being evil though...
Edit:For anybody who's sure their understanding of the subject is up to snuff should feel free to analyze the following and correctly predict its output before running it:
#include <stdio.h>
char *c[] = { "ENTER", "NEW", "POINT", "FIRST" };
char **cp[] = { c+3, c+2, c+1, c };
char ***cpp = cp;
main()
{
printf("%s", **++cpp);
printf("%s ", *--*++cpp+3);
printf("%s", *cpp[-2]+3);
printf("%s\n", cpp[-1][-1]+1);
return 0;
}
If memory serves, the credit (blame?) for that particular code goes to Thad Smith.
How did I do with this?
char strings[][11] = { "0123456789", "2222244444", "3333366666" };
printf("String 3 Character 2 is %c\n", *(*(strings + 2) + 1));