Skip to content

Commit 19be800

Browse files
vonzhouvonzhou
authored andcommitted
绝知此事要躬行
1 parent 9b95303 commit 19be800

File tree

8 files changed

+61
-0
lines changed

8 files changed

+61
-0
lines changed

chapter02/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,16 @@ show_bytes((byte_pointer)s, strlen(s));
9292
### 证明符号扩展的正确性, 利用数学归纳法,证明一位扩展正确即可
9393
![](sign_extension_prove.jpg)
9494

95+
### C语言标准:把short转换成unsigned时,先改变大小再完成从有符号到无符号的转换。 short -> int -> unsigned
96+
[type_cast_mystery.c](type_cast_mystery.c)
9597

98+
### 习题2.25 问题在于无符号运算, 0U - 1 = UMax, 然后访问非法地址,coredump
99+
[sum_elements.c](sum_elements.c)
100+
101+
### 习题2.26 问题仍然是无符号运算的微妙,size_t定义为unsigned int. 在做差和比较时会采用无符号运算,如果a<b, a-b是负数,会成为一个很大的无符号数,所以结果不正确
102+
[stronger.c](stronger.c)
103+
104+
###
96105

97106

98107

chapter02/sign_extension_prove.jpg

-246 Bytes
Loading

chapter02/stronger

8.32 KB
Binary file not shown.

chapter02/stronger.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
4+
int stronger(char *s, char *t){
5+
return strlen(s) - strlen(t) > 0;
6+
// return strlen(s) > strlen(t);
7+
}
8+
9+
int main(){
10+
char *s = "abc";
11+
char *t = "abcdef";
12+
printf("stringer = %d\n", stronger(s,t));
13+
return 0;
14+
}

chapter02/sum_elements

8.28 KB
Binary file not shown.

chapter02/sum_elements.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#include <stdio.h>
2+
3+
4+
int sum_elements(float a[], unsigned length){
5+
int i;
6+
float result = 0;
7+
for(i=0; i<=length-1;i++){
8+
result += a[i];
9+
}
10+
return result;
11+
}
12+
13+
int main(){
14+
int i = 0;
15+
unsigned len = 0U;
16+
printf("%u\n", len-1);
17+
return 0;
18+
}

chapter02/type_cast_mystery

8.28 KB
Binary file not shown.

chapter02/type_cast_mystery.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#include <stdio.h>
2+
3+
4+
typedef unsigned char *byte_pointer;
5+
6+
void show_bytes(byte_pointer start, int len){
7+
int i;
8+
for (i = 0; i < len; i++)
9+
printf(" %.2x", start[i]);
10+
printf("\n");
11+
}
12+
13+
int main(){
14+
short sx = -12345;
15+
unsigned uy = sx;
16+
17+
printf("uy = %u:\t", uy);
18+
show_bytes((byte_pointer)&uy, sizeof(unsigned));
19+
return 0;
20+
}

0 commit comments

Comments
 (0)