【发布时间】:2012-05-27 00:36:20
【问题描述】:
int main(int argc, char **args) {
unsigned char* str = "hallo";
printf("String: %s\n",str);
uint8_t aktion, id;
uint32_t str_length;
aktion = 1;
id = 4;
str_length = strlen(str)+1;
unsigned char *buff;
buff = (unsigned char*) calloc(1,str_length+6);
memcpy(buff, &id, sizeof(id));
memcpy(buff+sizeof(id), &str_length, sizeof(str_length));
strcpy(buff+sizeof(id)+sizeof(str_length), str);
printf("Buffer+5: %s\n",buff+5));
memcpy(buff+sizeof(id)+sizeof(str_length)+str_length, &aktion, sizeof(aktion));
return 0;
}
为什么我没有得到输出“你好”?我仍然不确定是否使用指针算法和缓冲区。
问候
【问题讨论】:
-
鉴于您转换
calloc的结果的方式,我认为这是C++。你应该使用std::string,而不是乱用裸指针。 -
那么你不应该投射
calloc的结果。 -
另外,赤裸裸的
1和5很奇怪。如果您已经知道尺寸,为什么还要打扰sizeof?最好的办法是在任何地方都写sizeof并且没有幻数,并将sizeof(uint8_t)替换为sizeof id等。 -
为什么,你能给我一些背景资料吗?省略演员表没有帮助。
-
不,它没有帮助,它只是更好的 C。这就是为什么它是一个评论 :-)
标签: c pointers char buffer void