Mail Archives: djgpp/1998/12/28/05:10:45
BJC wrote in message ...
>I still consider myself a begginer to C so maybe somebody can tell me whats
going on. I'm
>running a fresh install of DJGPP v2.02 with GCC v2.81. In the following
code i declare an
>array (str1) and initilize it to "TEST" and then i declare a second array
(str2). The problem
>is that the last element of str2 is allocated the same address as the first
element of str1.
No, sorryly this is a bug in you :-)
Let's look at the code:
> char str1[] = "TEST";
str1 allocates 5 bytes, because a string in C adds a '\0' char at it's end
> char str2[4];
str2 allocates 4 bytes
> int i;
> for (i=0;i<=sizeof(str2);i++)
sizeof(str2) is 4 (look above), so i=0, i<= sizeof(4) goes thru 5! elements
> printf("str2[%d] (%#xd) = \"%c\"\n",i,&str2[i],str2[i]);
> for (i=0;i<=sizeof(str1);i++)
same bug, traversing 6 elements
> printf("str1[%d] (%#xd) = \"%c\"\n",i,&str1[i],str1[i]);
> return;
>}
>str2[0] (0x8ecc4d) = " "
>str2[1] (0x8ecc5d) = " "
>str2[2] (0x8ecc6d) = " "
>str2[3] (0x8ecc7d) = " "
>str2[4] (0x8ecc8d) = "T" <------------ same address
str2[4] is an address outside str2
>str1[0] (0x8ecc8d) = "T" <------------ same address
>str1[1] (0x8ecc9d) = "E"
>str1[2] (0x8eccad) = "S"
>str1[3] (0x8eccbd) = "T"
>str1[4] (0x8ecccd) = " "
>str1[5] (0x8eccdd) = " "
str1[5] is an address outsize str1
>i compiled this program with DJGPP 2.01 and PGCC 1.01 and all was
well...infact it left 2
>bytes space between str2 and str1.
It's difficult to say why. Maybe the optimizers in this compilers think,
that the strings should be allocated
8 bytes aligned...
So the problem is your for loop. Note, that in C the typical construct for
traversing n elements is
for (i = 0; i < n; ++i)
cheers,
--
Michael Beck, email: beck AT dresearch DOT de
- Raw text -