简体   繁体   中英

Why would this work: Array of pointers to C strings?

Why would such checking *(string + i) don't pass after all strings are printed? The output of printf("%p", string + i + 1); definitely shows string + i + 1 isn't NULL.
I've tried this code several times with several quantity of strings.
Maybe some of C guru can give answer to this? Thanks in advance. :-)

The code:

#include <stdio.h>

int
main(void)
{
        size_t i;
        char *string[] = {
                "Hey, baby!",
                "How are ya?",
                "What the heck is going on in here?"
        };

        for (i = 0; *(string + i); ++i)
        {
                printf("%s\t%p\n", *(string + i), string + i);
        }

        printf("%p", string + i + 1);

        return 0;
}

The output:

[aenry@MintK50ID 2]$ ./test   
Hey, baby!  0x7fff691978e0
How are ya? 0x7fff691978e8
What the heck is going on in here?  0x7fff691978f0
0x7fff69197900%

[aenry@MintK50ID 2]$ gcc -v   
...
gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu9)

--------Edit: It turned out, this is really junk code and somehow only gcc compiles it in a way it works. UB nuff said. Thanks, guys.

You can't expect this to work: for (i = 0; *(string + i); ++i) .

The fact that each string ends with a 0 character, doesn't mean that an array of strings ends with a NULL pointer.

So *(string + i) is an illegal memory access as soon as i becomes larger than 2.

Change the above to: for (i=0; i<sizeof(string)/sizeof(*string); ++i) .

You are in the world on undefined behaviour - so anything can happen.

Just add a NULL to the end of the array

String literals are null terminated implicitly: "Hello" becomes { 'H', 'e', 'l', 'l', 'o', '\\0' } behind the scenes (and it becomes array with 6 slots).

But the above applies only for strings ( char arrays), and only if they are created using a string literal or a function that has already taken care of adding a null terminator. Other kinds of arrays (including arrays of strings, like you have here), aren't necessarily null terminated. Of course, you can make them null terminated by adding the null manually at the end, as long as the array has one extra slot to store the null.

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