将指针变量作为指向C中其他类型的指针进行访问

时间:2019-05-18 14:51:02

标签: c pointers strict-aliasing

通过取消指向指向不同类型或if(clickedCells[0] && clickedCells[1] && clickedCells[2] !== "" && clickedCells[0] === clickedCells[1] && clickedCells[0] === clickedCells[2]){ done(); } 的指针的指针来访问指针变量是一种好习惯吗?这可以打破严格的别名规则吗? C和C ++在别名规则上有一些区别。在这个问题中,我们专注于C。考虑C ++的其他问题可以在here中找到。在以下示例中,将void作为double*进行访问。

void*

以下各项是否更好:

int create_buffer(void** ptr, ...)
{
    *ptr = malloc(...);
    ...
}

int main(void)
{
    double* buffer;

    // The problematic code is here, double**
    // is coerced to void**, which is later
    // dereferenced by the function
    create_buffer((void**)&buffer, ...);
    ...
}

2 个答案:

答案 0 :(得分:0)

不回答您的问题,但是您可以通过做明确定义的事情来解决提到的不确定性:

=ARRAYFORMULA(IF(LEN(A1:A), 
 IF(IFERROR(REGEXEXTRACT(A1:A, "\...$|\?$|!$|—$|\.$"))<>"", 1, 0), ))

答案 1 :(得分:0)

我宁愿这样写,假设您使用“ int”向调用者返回一些有用的信息,而这些信息离不开:

void *create_buffer(size_t n, int *otherInfo) {
    void *ptr = malloc(n);
    *otherInfo = 0;
    if (ptr) {
        // Do whatever other initialization is expected
        // memset(ptr, 0, n);
    } else {
        *otherInfo = -1;
    }
    return ptr;
}

int main(void)
{
    double* buffer;
    int code;

    /* cast is not required by language or compiler, 
       but I still find it useful when reading */
    buffer = (double *)create_buffer(SIZE_REQUIRED, &code);

    /* equality testing can be done either way. This way here,
       if you ever forget a =, will never compile anywhere. Nowadays
       many compilers are smart enough to catch it on their own anyway */
    if (NULL == buffer) {
        // Handle out of memory error or other problem
        switch(code) {
            case -1:
                fprintf(stderr, "Out of memory\n");
            ...
            default:
                fprintf(stderr, "Unexpected error %d\n", code);            
                break;
        }
    }
}