简体   繁体   English

无法初始化C数组

[英]Unable to initialize c array

I was writing some low level c code on fedora 14, but going nuts over this piece of code. 我在fedora 14上写了一些低级的c代码,但是在这段代码上有些胡扯。 The first array is not initialized to '0', the second is. 第一个数组未初始化为“ 0”,第二个数组未初始化。 Gone through gdb several times, but it's like magic. 多次遍历gdb,但这就像魔术。 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] . 我在gdb内打印了数组值,分别为p nump tnump num[0]p tnum[0] I also tried to initialize as plain 0, same thing also happens. 我也尝试初始化为纯0,同样的事情也发生了。

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) 

What is maxsize ? 什么是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: 另外,您不应该重复神奇的常量,for循环最好写成:

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() : 或者,由于这些是char数组,只需使用memset()

#include <string.h>

memset(num, '0', sizeof num);
memset(tnum, '0', sizeof tnum);

How do you check you array are initialized with the '0' character literal? 您如何检查数组是否以'0'字符文字初始化? If you print them as strings, remember string are null terminated and your arrays are not. 如果将它们打印为字符串,请记住string是以null结尾的,而数组不是。

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 . 还要注意'\\0'int0 ,而'0'可打印字符0

You should use memset for both of your arrays: 您应该对两个数组都使用memset:

#include <string.h>
char num[7];
memset(num, '\0', sizeof(num));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM