在带有0的64位环境中打印%lu会给出140733193388032输出。

我在64位环境中打印了8次0,直到第6位的值打印为0,最后2次正在打印140733193388032

#include <stdio.h>

struct size {
    unsigned long length;
    unsigned long breadth;
};

struct pad {
    unsigned long len;
    unsigned long bre;
    unsigned char hei;
    unsigned char pad[7];
};

int main() {
    unsigned long a;
    unsigned long b = 0;
    struct size sz;
    struct pad sz1;

    printf("%lu is a, %lu is b , %lu is length, %lu is breadth, %lu is len, "
           "%lu is bre, %lu is hei, %lu is zero\n",
           a, b, sz.length, sz.breadth, sz1.len, sz1.bre, sz1.hei, 0);
    printf("%lu is a, %lu is b , %lu is length, %lu is breadth, %lu is len, "
           "%lu is bre, %lu is hei, %lu is zero",
           0, 0, 0, 0, 0, 0, 0, 0);
}


输出:

140737488347824 is a, 0 is b , 0 is length, 4195408 is breadth, 140737346312864 is len, 4195893 is bre, 140733193388064 is hei, 140733193388032 is zero
0 is a, 0 is b , 0 is length, 0 is breadth, 0 is len, 0 is bre, 140733193388032 is hei, 140733193388032 is zero

With Initializing struct and local:

#include <stdio.h>

struct size {
    unsigned long length;
    unsigned long breadth;
};

struct pad {
    unsigned long len;
    unsigned long bre;
    unsigned char hei;
    unsigned char pad[7];
};

int main() {
    unsigned long a = 0;
    unsigned long b = 0;
    struct size sz = { 0 };
    struct pad sz1 = { 0 };

    printf("%lu is a, %lu is b , %lu is length, %lu is breadth, %lu is len, "
           "%lu is bre, %lu is hei, %lu is zero\n",
           a, b, sz.length, sz.breadth, sz1.len, sz1.bre, sz1.hei, 0);
    printf("%lu is a, %lu is b , %lu is length, %lu is breadth, %lu is len, "
           "%lu is bre, %lu is hei, %lu is zero",
           0, 0, 0, 0, 0, 0, 0, 0);
}


输出:

0是a,0是b,0是长度,0是宽度,0是len,0是bre,140733193388032是hei,140733193388032是零
0是a,0是b,0是长度,0是宽度,0是len,0是bre,140733193388032是hei,140733193388032是零

最佳答案

您要引用的变量未初始化,并且包含内存中的一些垃圾。编译器没有必要进行零初始化,因此数字是零。在声明时将所有变量初始化为零,如下所示:

memset(&sz, 0, sizeof(sz))

或所有成员分开。

提供摘要后进行编辑

我试图将所有变量归零初始化,如下所示:

#include <stdio.h>
struct size
{
  unsigned long length;
  unsigned long breadth;
};

struct pad
{
  unsigned long len;
  unsigned long bre;
  unsigned char hei;
  unsigned char pad[7];
};


int main()
{

  unsigned long a = 0;
  unsigned long b = 0;
  struct size sz = { 0 };
  struct pad sz1 = { 0 };

  printf("%lu is a, %lu is b , %lu is length, %lu is breadth, %lu is len, %lu is bre, %lu is hei, %lu is zero\n",a,b,sz.length, sz.breadth, sz1.len, sz1.bre, sz1.hei, 0);
  printf("%lu is a, %lu is b , %lu is length, %lu is breadth, %lu is len, %lu is bre, %lu is hei, %lu is zero",0,0,0,0,0,0, 0, 0);
 }


我得到以下输出:

0 is a, 0 is b , 0 is length, 0 is breadth, 0 is len, 0 is bre, 0 is hei, 0 is zero
0 is a, 0 is b , 0 is length, 0 is breadth, 0 is len, 0 is bre, 0 is hei, 0 is zero

关于c - 64位环境中的printf/snprintf行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55805099/

10-11 07:29