2013-10-28 119 views
2

我正在学习C++,我们正在研究预处理器,但我试图解决一个测验中的一个问题,这个问题让我有点困惑或者很多..我试图在运行程序..和我的输出以2为..C++定义预处理器

系统开始...
数据是:在1 27 28 29 30
数据是:23 24 25 26
的数据是:19

我在Xcode中检查了程序t Ø看看我的输出是正确的,但正确的输出是下一个:

系统开始...
数据以1:0 0 0 0 19
数据是:7 0 0 0
的数据是:19 0 0 0

这是代码...

#include <iostream> 

namespace test{ 
#define COMPILE_FAST 
#define PRINT_SPLIT(v) std::cout << (int)*((char*)(v)) << ' ' << \ 
(int)*((char*)(v) + 1) << ' ' << (int)*((char*)(v) +2) << ' ' << \ 
(int)*((char*)(v) + 3) << std::endl 

    typedef unsigned long long uint; 
    namespace er{ 
     typedef unsigned int uint; 
    } 
    void debug(void* data, int size = 0){ 
     if(size==0){ 
      std::cout << "The data is: "; 
      PRINT_SPLIT(data); 
     } else { 
      while(size--){ 
       std::cout << "Data at " << size << " is: "; 
       char* a = (char*)data; 
       PRINT_SPLIT((a + (4+size))); 
      } 
     } 
    } 
}// End of Test namespace... 

int main(){ 
    test::uint a = 19; 
    test::er::uint b[] = {256,7}; 
    std::cout << "System started..." << std::endl; 
    test::debug(b,2); 
    test::debug(&a); 
    std::cout << "Test complete"; 
    return 0; 
} 

我最大的疑问还是什么其实我不明白是什么回事呢在这种预处理,因为显然对我所做的完全错误的......

#define PRINT_SPLIT(v) std::cout << (int)*((char*)(v)) << ' ' << \ 
(int)*((char*)(v) + 1) << ' ' << (int)*((char*)(v) +2) << ' ' << \ 
(int)*((char*)(v) + 3) << std::endl 

如果有人能这么漂亮,给我一个简要的解释,我将非常感激。

+0

' 4 + size'应该是'4 * size'(或者更好,sizeof(int)* size') –

回答

1

该宏打印4个连续字节的值(如整数)。它可以让你看到如何在内存中放置一个4字节的int。

存储器中的内容,由字节,如下所示(base10):

0x22abf0:  0  1  0  0  7  0  0  0 
0x22abf8:  19  0  0  0  0  0  0  0 
  • 0 1 0 0是256,即B [0]
  • 7 0 0 0是7,即字母b [1]
  • 19 0 0 0 0 0 0 0是19,即

sizeof(a)sizeof(b[0])不同,因为有2周不同的typedef为uint。即,test:uinttest::er::uint

即使在a之后声明b,因为堆栈在内存中向下增长,所以地址a大于地址b[]

最后,我要说的输出代表有缺陷的程序,因为输出会更加合理地:

System started... 
Data at 1 is: 7 0 0 0 
Data at 0 is: 0 1 0 0 
The data is: 19 0 0 0 

要获得输出的程序需要进行如下修改:

  while(size--){ 
      std::cout << "Data at " << size << " is: "; 
      int* a = (int*)data; 
      PRINT_SPLIT((a + (size))); 
+0

非常感谢..我更了解那里发生了什么.. – valbu17