public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* odd behavior with Character Arrays
@ 2008-08-08  6:55 Rohit Arul Raj
  2008-08-08  7:07 ` Mateusz Loskot
  0 siblings, 1 reply; 12+ messages in thread
From: Rohit Arul Raj @ 2008-08-08  6:55 UTC (permalink / raw)
  To: gcc-help

Hi All,

Compiler Version: gcc 4.1.2 and gcc 3.4.6

Test Case:

unsigned int g = 0;
unsigned int slen(const char* c)
{
        int l = 0;
        while(*c != '\0') {
                ++l;
                ++c;
        }
        return l;
}

int main()
{
        unsigned int t;
        unsigned char n[] = {'a', 'b', 'c', 'd'};
        t = slen(n);
        g = slen(n);

        printf("\n t = %d, g1 = %d\n", t, g1);
        return 0;
}

I have a test case given above which is used to compute the string
length of the character array. In the test case, both 't' and 'g' call
the same function to compute the string length. But both these values
are different and they are wrong also.

With GCC 4.1.2,  t = 7, g = 5
With GCC 3.4.6,  t = 15, g = 5

This happens only when i don't provide the size of the array 'n'. If
size of the array is given "unsigned char n[15] = {'a', 'b', 'c',
'd'};" then the values are proper
t = 4 and g = 4.

1. Is this the expected behavior with GCC?
2. Can i get more details as to why if the size of the array is not
provided the compiler does not insert an string terminator at the end
of the array.
    This happens with both character as well as integer arrays.

Regards,
Rohit

^ permalink raw reply	[flat|nested] 12+ messages in thread

end of thread, other threads:[~2008-08-09 11:23 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2008-08-08  6:55 odd behavior with Character Arrays Rohit Arul Raj
2008-08-08  7:07 ` Mateusz Loskot
2008-08-08  9:38   ` Rohit Arul Raj
2008-08-08 12:10     ` Jędrzej Dudkiewicz
2008-08-08 13:00     ` Mateusz Loskot
2008-08-08 13:40       ` Mateusz Loskot
2008-08-08 15:01     ` John Fine
2008-08-09  1:09       ` Is this code wrong? John Fine
2008-08-09  2:44         ` Eljay Love-Jensen
2008-08-09 11:23           ` corey taylor
2008-08-09 14:57             ` John Fine
2008-08-08 15:38     ` odd behavior with Character Arrays Bob Plantz

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).