0

I have an array of pointers to characters:

char *myStrings[40];

Eventually, myStrings[0] will equal "example" or something of the sort. I'd like to check the first character and see if it's equal to e.

Thanks for the help!

3
  • 4
    if((*myStrings)[0] == 'e') Commented Dec 10, 2017 at 0:14
  • 1
    You have an array of pointers to char (char *[]), not a pointer to an array of char (char (*)[]). Commented Dec 10, 2017 at 0:15
  • 2
    You know that myStrings[0] is a "string". Now do you know how to access an arbitrary characters of a string? What if you have char *mySingleString;, how would you then access the first character of that? Commented Dec 10, 2017 at 0:18

2 Answers 2

3

A pointer is a variable that holds the address to something else as its value. To access the value at the address held by the pointer (e.g. the something else), you dereference the pointer with the unary '*'.

Since you have an array of pointers, you will need to dereference the first element of the array, e.g. mystrings[0]. With C - operator precedence, the [..] has greater precedence than '*', so you can simply look at the first character of the string pointed to by mystrings[0] by dereferencing the pointer, e.g. *mystrings[0]

A short example will help:

#include <stdio.h>

#define MAX 40

int main (void) {

    char *string = "example",       /* string literal */
        *arrptrs[MAX] = { NULL };   /* array of pointers */

    arrptrs[0] = string;    /* set 1st pointer to point to string */

    if (*arrptrs[0] == 'e')         /* test 1st char is 'e' */
        printf ("found : %s\n", arrptrs[0]);

    return 0;
}

Since you are looking at the first element of your array of pointers, you can also print the string "example" by dereferecing the array, e.g.

        printf ("found : %s\n", *arrptrs);

Example Use/Output

$ ./bin/arrptrs
found : example

(the output is the same regardless whether you access the first element with arrptrs[0] or *arrptrs, they are equivalent -- do you understand why?)

note: always pay attention to C-Operator Precedence. Let me know if you have further questions.

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

Comments

2

Each element of this array is a string, then consider that we have:

char *myStrings[40] = {"Example", " 01", " - ", "Hello", ",World!\n"};

so

myStrings[0] is equals to "Example" 
myStrings[1] is equals to " 01"
... 

Now, we have to access the first element of *myStrings[0] by this way

*(myStrings)[0] or *myStrings[0]

if (*(myStrings)[0] == 'E'){
    do something
}

or

if (*myStrings[0] == 'E'){
    do something
}

1 Comment

*myStrings[0] = "Example" - typo, shouldn't have *?

Your Answer

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