MMH MMH - 2 months ago 6
C Question

accessing the elements of a char*

I have a

char *p = "abcd"
, how can I access the elements
'a','b','c','d'
using only C(not C++)? Any help would be appreciated .

Answer

You can use indexing:

 char a = p[0];
 char b = p[1];
 /* and so on */

Equivalently you can use pointer arithmetic, but I find it less readable:

char a = *p;
char b = *(p+1);

If you really want to surprise someone you can also write this:

 char a = 0[p];
 char b = 1[p];
 /* and so on */