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 .
Use the array subscript operator [] . It allows you to access the nth element of a pointer type in the form of p[n] . You can also increment the pointer by using the increment operator ++ .
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.
This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With