简体   繁体   中英

Check first character of a pointer to an array

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!

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 (eg 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, eg 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, eg *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, eg

        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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM