小编pup*_*007的帖子

C中的符号扩展,char>unsigned char

当我阅读 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?

c casting char bit

4
推荐指数
1
解决办法
1709
查看次数

是否指向void的指针总是安全的?

#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总是安全的,或者是否有任何替换它的方法.

c pointers void

3
推荐指数
1
解决办法
458
查看次数

Python sys._getframe

/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 错误,但可以正常打印?谢谢~

python

2
推荐指数
1
解决办法
5266
查看次数

标签 统计

c ×2

bit ×1

casting ×1

char ×1

pointers ×1

python ×1

void ×1