当我阅读 K&R 时,我对这段代码感到困惑:
#include "syscalls.h"
int getchar(void)
{
char c;
return (read(0, &c, 1) == 1) ? (unsigned char)c : EOF;
}
Run Code Online (Sandbox Code Playgroud)
据说unsigned char是为了避免这段代码中符号扩展带来的错误。这是我能想到的唯一情况,我给出了这个示例代码:
char c = 0xf0; //11110000, just make highest bit > 1
printf("%i\n",(int)(unsigned char)c);
printf("%i\n",(int)c);
Output: 240 // 0...011110000
-16 // 1...111110000
Run Code Online (Sandbox Code Playgroud)
但实际上 ascii 只是 0~127 最高位不能分配给 1.Why in K&R cast char >> unsigned char?
#include <stdio.h>
void swap(void *v[], int i, int j)
{
void *tmp;
tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
int main(void)
{
char *s[] = {"one", "two"};
printf("%s, %s\n", s[0], s[1]);
swap(s, 0, 1);
printf("%s, %s\n", s[0], s[1]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
one, two
two, one
Run Code Online (Sandbox Code Playgroud)
警告: no compatible pointer casting, need void**, but char
我使用这个程序来模拟K&R中的交换函数,以演示函数指针的使用,我的问题是它的转换是否void pointer总是安全的,或者是否有任何替换它的方法.
/mypath/test.py
import sys
def test():
frame = sys._getframe(0)
f = frame.f_code.co_filename
print('f:', f)
print('co_filename1:', frame.f_code.co_filename)
while frame.f_code.co_filename == f:
frame = frame.f_back
print('co_filename2:', frame.f_code.co_filename)
test()
Run Code Online (Sandbox Code Playgroud)
运行它并得到:
f: /mypath/test.py
co_filename1: /mypath/test.py
Traceback (most recent call last):
File "/mypath/test.py", line 13, in <module>
test()
File "/mypath/test.py", line 9, in test
while frame.f_code.co_filename == f:
AttributeError: 'NoneType' object has no attribute 'f_code'
Run Code Online (Sandbox Code Playgroud)
为什么 frame.f_code 在 while 循环中出现 NoneType 错误,但可以正常打印?谢谢~