1. 函数中传参数组
http://c.biancheng.net/view/207.html
需要传递数组元素的个数
void print_array(int arr[], int size)
2. 函数返回值类型问题
a.c
long long func1() {
return -1;
}
b.c
printf("%lld\n", func1());
打印会出错,因为没有函数声明的话,默认是返回int类型
3. 鼠标对应的文件/dev/input/mouse0
4. 套接字使用
https://www.ibm.com/developerworks/cn/linux/l-sockpit/
5. 结构体类型强制转换
无法转换结构体变量,只能转换结构体指针。
struct sa
{
int a;
};
struct sb
{
int a;
};
int main(void)
{
struct sb s2 = {321};
//struct sa s1 = (struct sa)s2; //错误,编译error
struct sa *psa = (struct sa*)&s2; //必须这样转
}
6. c语言不支持三元运算!!!
错误引出
unsigned char char_to_hex(char cha)
{
if ('0' <= cha <= '9') {
return cha - '0';
}
if ((cha >= 'a') && (cha <= 'f'))
return cha - 'a' + 10;
if ((cha >= 'A') && (cha <= 'F'))
return cha - 'A' + 10;
return 0;
}
以上代码在把字符转为数字的时候,出现错误,字符a-f都会进入第一行。就是因为三元运算导致的。
int main()
{
int a = 10;
if (0 < a < 2) {
printf("yes\n");
}
else {
printf("no\n");
}
return 0;
}
//yes
7. 运算符优先级
字符串mac转char存放
要注意:字符要转为数字,使用<<的话要注意优先级,加括号
unsigned char char_to_hex(char cha)
{
if (('0' <= cha) && (cha <= '9')) {
return cha - '0';
}
if ((cha >= 'a') && (cha <= 'f'))
return cha - 'a' + 10;
if ((cha >= 'A') && (cha <= 'F'))
return cha - 'A' + 10;
return 0;
}
void mac_str_to_char(const char *strmac, unsigned char *buf)
{
int i = 0;
int j = 0;
char a, b;
for (; j < 6;) {
if (strmac[i] == ':')
i+=1;
else
{
//buf[j] = char_to_hex(strmac[i]) << 4 + char_to_hex(strmac[i+1]);
buf[j] = (char_to_hex(strmac[i]) << 4) + char_to_hex(strmac[i+1]);
i += 2;
j++;
}
}
return;
}
a0:ff:f3:d0:c4:e1如果<<没有加括号,转换后为a0 00 80 d0 00 c0,加括号后为a0 ff f3 d0 c4 e1
因为+号运算符优先级高于<<
8. 强制类型转换
数据打印或存取时,尤其是char类型,要考虑范围。
比如ioctl获取mac地址,存在struct sockaddr的char sa_data[14]里面,那么打印sa_data的mac是要先转为unsigned char,不然会出错误。
比如mac是fa:aa:14:53:6c:c4
如果直接打印就是fffffffc:ffffffaa:14:53:6c:ffffffc4
9. open打开tty*之类的终端接口
使用了标志O_RDWR | O_NOCTTY | O_SYNC
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
 数组定义长度小了
char buf1[4] = "abcd";
/usercode/file.cpp: In function ‘int main()’:
/usercode/file.cpp:26:20: error: initializer-string for array of chars is too long [-fpermissive]
char buf1[4] = "abcd";
(2) sizeof strlen
char buf1[8] = "abcd";
char buf2[] = "abcd";
printf("strlen(buf1) = %lu\n", strlen(buf1));
printf("strlen(buf2) = %lu\n", strlen(buf2));
printf("sizeof(buf2) = %lu\n", sizeof(buf2));
strlen(buf1) = 4
strlen(buf2) = 4
sizeof(buf2) = 5
12. 循环语句
循环语句的初始化最好写在括号内,防止遗忘出错。
可以不跟大括号{},如果只是执行下面一句
for(; i < 4; i++)
for(; j < 4; j++)
for(; k < 4; k++)
if ((i != j) && (j != k) && (i != k)) {
printf("%d%d%d\n", i, j, k);
}
printf("bye bye\n");
root@ubuntu:/mnt/hgfs/winshare/test# ./test
bye bye
int i = 1, j = 1, k = 1;
for(i = 1; i < 4; i++)
for(j = 1; j < 4; j++)
for(k = 1; k < 4; k++)
if ((i != j) && (j != k) && (i != k)) {
printf("%d%d%d\n", i, j, k);
}
printf("bye bye\n");
123
132
213
231
312
321
bye bye