13

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 .

6 Answers 6

22

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 */
3
  • 3
    I'd rather not advertise the third alternative to beginners without explicitly mentioning that it's a bad practice.
    – user694733
    Nov 12, 2014 at 9:50
  • 1
    I wouldn't recommend using pointer arithmetic for this case either, but there's value in knowing that the three methods exist
    – Joni
    Nov 12, 2014 at 9:57
  • 2
    @karoly I'm saying that using anything but direct indexing (the first option) is insanity.
    – Joni
    Nov 12, 2014 at 10:07
4

Here, p refers an array of character pointer. You ca use the array indexing to access each variable in that array. The most widely used notation for this is p[n], where n is the n+1th character [element].

example:

for the 1st character, use p[0], 2nd character, use p[1] and so on..

4

another example:

#include <stdio.h>

int main()
{
    char *p="abcd";
    for (; *p; p++)
        printf("%c\n", *p);
    return 0;
}

result is:

a
b
c
d
2

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

1
#include <stdio.h>

int main()
{
    char *p="abcd";
    printf("%c\n", p[0]);
    printf("%c\n", p[1]);
    printf("%c\n", p[2]);
    printf("%c\n", p[3]);
    return 0;
}

returns

a
b
c
d
1
#include <stdio.h>
#include <stdlib.h>

void main()
{
    char* str="Hello, World!";
    printf("%s\n",str);
}

Output:

Hello, World!

2nd Method:

#include <stdio.h>
#include <stdlib.h>

void main()
{
    char* str="Hello";
    int n=strlen(str);
    for(int i=0;i<n;i++)
    {
        printf("%c"str[i]);
    }
}

Output:

Hello

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.