0
// 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] ?

4
  • Sounds like homework to me. What are you having trouble understanding? Commented Dec 9, 2009 at 2:25
  • 15
    The index operator is pointer arithmetic in disguise. Commented Dec 9, 2009 at 2:26
  • 1
    I don't see anything wrong with this question; after all it's what SO is intended for, is it not? (if we ignore the possibility of it being homework). Commented Dec 9, 2009 at 6:12
  • needs more detail, seems like homework. If you mean 'how can I iterate through these array elements' then please update the question. Commented Dec 31, 2009 at 8:24

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

Comments

0

How did I do with this?

char strings[][11] = { "0123456789", "2222244444", "3333366666" }; 
printf("String 3 Character 2 is %c\n", *(*(strings + 2) + 1));

1 Comment

Pretty poorly. It's strings[2][1] in the example. You're printing out a nonexistent strings[3][1]. Also, you don't need the & operator here - it's harmless, but totally superfluous.
0
 *(*(strings+2)+1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.