1

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.

3 Answers 3

3

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

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

2 Comments

Thank you. Just got wonder why such code copiled in gcc works. After all checked in clang and VS2010 and they do bark at this. Got segfalts. Yet it is still strage gcc understood such junk :)
Nothing says it can't work, but nothing says it will always work.
1

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

Just add a NULL to the end of the array

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.