开发过程中的各种愚蠢错误

printf不足?

今天记录一个愚蠢的错误。

#include <stdint.h>

int main()
{
	uint64_t a;
	uint64_t b;
	a = 0x999;
	b = 0x888;
	printf("uint64_t size : %dB, uint size: %dB\n", sizeof(unsigned long long), sizeof(unsigned int));
	printf("a: %x b: %x\n", a, b);
	return 0;	
}

输出结果:

uint64_t size : 8B, uint size: 4B
a: 999 b: 0

我们预期b的值应该是888。

因为%x只输出4B(unsigned int)的数据,而a是8B,相当于后一个%x输出的是a的另外4B。
我们可以写一段代码测试一下:

printf("a: %x %x, b: %x %x\n", a, b);

输出是:

a: 999 0, b: 888 0

所以本例更深刻的理解printf的格式代码,格式代码只是决定从起始地址拿出多少数据,与后面的内容并无一一对应关系。所以一定要注意格式代码与实际数据的大小对应。

(据同事说这个问题很常见。。。还是C的基础不够牢。。。)

define中的括号

这个错误真的羞愧。。。

#include<stdio.h>
#define TEST sizeof(int) + sizeof(double)
#define TEST_A (sizeof(int) + sizeof(double))
int main()
{
	printf("%d %d\n", 100 - TEST. 100 - TEST_A);
	return 0;
}

/* stdout:
 * 104 88
 * 100 - TEST = 100 - sizeof(int) + sizeof(double)
 * 100 - TEST_A = 100 - (sizeof(int) + sizeof(double))

别的不说了,一下午时间耽误在这。。。

指针的加减常数时要注意转换类型

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct test{
	int a;
	int b;
	struct test* next;
} test_t;

int main()
{
	test_t* t1 = (test_t*)malloc(sizeof(test_t));
	test_t* t2 = (test_t*)malloc(sizeof(test_t));
	printf("%lx\n", t1 - 2);
	printf("%lx\n", (uint64_t)t1 - 2);		
	return 0;
}

新完成cpp文件之后别忘了改Makefile

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值