请你解释一下输出并指出错误

时间:2011-03-14 08:25:54

标签: c++ arrays gcc memset

char FramebufferUpdateRequest[11];
uint16_t val;
memset(FramebufferUpdateRequest, 0, 10);
FramebufferUpdateRequest[0] = 3;
FramebufferUpdateRequest[1] = 1;
val = 3;
memcpy(FramebufferUpdateRequest+6, &val, 2);
val = 2;
memcpy(FramebufferUpdateRequest+8, &val, 2);
FramebufferUpdateRequest[10]='\0';
printf("framerequest :: %c  %s\n", FramebufferUpdateRequest[1], FramebufferUpdateRequest);

这个printf的输出是空白,即“framerequest ::”。任何人都可以指出我做错了什么?

在gcc 4.1.2中编译

2 个答案:

答案 0 :(得分:1)

您正在为FramebufferUpdateRequest分配不可打印的字符。

您需要以某种方式将其转换为整数(即​​使用循环和%d)或可打印字符(例如,将'A'添加到每个元素)。

显示基本的可打印字符集at Wikipedia

答案 1 :(得分:1)

我想你想写:

memset(FramebufferUpdateRequest, 0, 10);
FramebufferUpdateRequest[0] = '3'; //notice the difference
FramebufferUpdateRequest[1] = '1'; //notice the difference
val = '3';  //or var = ('3' << 1 | '3') if you want both bytes to have '3'
memcpy(FramebufferUpdateRequest+6, &val, 2);
val = '2';  //or var = ('2' << 1 | '2') if you want both bytes to have '2'

了解'1'1

之间的区别
   cout << (int) ('1') << endl;
   cout << (int) (1) << endl;

输出:(http://www.ideone.com/z3spn

49
1

说明:'1'character literal,其ascii值为49,而1是整数。