Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing the elements of a char*

Tags:

c

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 .

like image 238
MMH Avatar asked Nov 12 '14 09:11

MMH


People also ask

How do I access the elements of a char pointer?

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 ++ .

What does char * mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

Is char * a string?

char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.

Is char * A string in C?

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.


1 Answers

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 */
like image 66
Joni Avatar answered Sep 22 '22 15:09

Joni