Reputation: 59
I was writing some low level c code on fedora 14, but going nuts over this piece of code. The first array is not initialized to '0', the second is. Gone through gdb several times, but it's like magic. What is happening?
const int maxsize=100000;
char num[7];
char tnum[6];
int pos=0;
while(pos<(maxsize+1)) {
int c=0;
int j=0;
int myindex;
int tindex;
for(myindex=0;myindex<7;myindex++) num[myindex]='0';
for(tindex=0;tindex<6;tindex++) tnum[tindex]='0';
//....
}
I printed the array values inside gdb
, both as p num
, p tnum
and as p num[0]
and p tnum[0]
.
I also tried to initialize as plain 0, same thing also happens.
Here is the debugger output
Temporary breakpoint 1, main () at inversionscount.c:3
3 int main() {
Missing separate debuginfos, use: debuginfo-install glibc-2.13-1.i686
(gdb) s
5 const int maxsize=100000;
(gdb) s
6 int startarray[maxsize];
(gdb) s
14 int pos=0;
(gdb) s
15 while(pos<(maxsize+1)) {
(gdb) s
19 int c=0;
(gdb) s
20 int j=0;
(gdb) s
24 for(myindex=0;myindex<7;myindex++) num[myindex]='0';
(gdb) s
25 for(tindex=0;tindex<6;tindex++) tnum[tindex]='0';
(gdb) s
27 while( c=getchar()!="\n") {
(gdb) p num
$1 = "\370\377\277\270\367\377"
(gdb) p tnum
$2 = "000000"
(gdb)
Upvotes: 2
Views: 313
Reputation: 1208
You should use memset for both of your arrays:
#include <string.h>
char num[7];
memset(num, '\0', sizeof(num));
Upvotes: 0
Reputation: 145899
How do you check you array are initialized with the '0'
character literal? If you print them as strings, remember string are null terminated and your arrays are not.
Add this:
num[sizeof num - 1] = '\0';
tnum[sizeof tnum - 1] = '\0';
before printing them:
printf("%s\n", num);
printf("%s\n", tnum);
Also notice '\0'
is the int
value 0
while '0'
is the printable character 0
.
Upvotes: 0
Reputation: 400009
What is maxsize
? Make sure the code follows the execution path you think it does, by single-stepping through with a debugger.
Also, you shouldn't repeat magical constants, the for loops are better written as:
size_t i;
for(i = 0; i < sizeof num; ++i)
num[i] = '0';
for(i = 0; i < sizeof tnum; ++i)
tnum[i] = '0';
or, since these are char
arrays, just use memset()
:
#include <string.h>
memset(num, '0', sizeof num);
memset(tnum, '0', sizeof tnum);
Upvotes: 1