Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么是局部变量指针?_C - Fatal编程技术网

C 为什么是局部变量指针?

C 为什么是局部变量指针?,c,C,在这段代码中(摘自qemacs的源代码) static int goto_char(u8*buf,int pos,QECharset*charset) { 国际nb_chars,c; u8*buf_ptr; if(字符集!=&charset\u utf8) 返回pos; nb_chars=0; buf_ptr=buf; 对于(;;){ c=*buf_ptr; 如果(c=0xc0){ 如果(注意字符>=位置) 打破 nb_chars++; } buf_ptr++; } 返回buf_ptr-buf;

在这段代码中(摘自qemacs的源代码)

static int goto_char(u8*buf,int pos,QECharset*charset)
{
国际nb_chars,c;
u8*buf_ptr;
if(字符集!=&charset\u utf8)
返回pos;
nb_chars=0;
buf_ptr=buf;
对于(;;){
c=*buf_ptr;
如果(c<0x80 | | c>=0xc0){
如果(注意字符>=位置)
打破
nb_chars++;
}
buf_ptr++;
}
返回buf_ptr-buf;
}

为什么不直接访问buf而不是创建一个局部变量指针?

如果增加
buf
,则会丢失原始
buf
地址的跟踪,从而丢失长度

有两种解决方案:要么保留原始变量的副本,使用另一个临时移动指针来增加buf指针,要么保留一个索引计数器

这个实现使用了第二个。此外,还有许多程序员为了避免任何意外而避免更改函数参数

虽然您可以避免使用
buf\u ptr
并使用
buf[某些索引+++]
,但当使用
步行指针而不是索引时,一些古老的编译器可以生成更快的代码


相关:

他们会怎么做
buf_ptr++
返回buf_ptr-bufstatic int goto_char(u8 *buf, int pos, QECharset *charset)
{
    int nb_chars, c;
    u8 *buf_ptr;

    if (charset != &charset_utf8)
        return pos;

    nb_chars = 0;
    buf_ptr = buf;
    for(;;) {
        c = *buf_ptr;
        if (c < 0x80 || c >= 0xc0) {
            if (nb_chars >= pos)
                break;
            nb_chars++;
        }
        buf_ptr++;
    }
    return buf_ptr - buf;
}