pointer to array not compatible to a pointer to 'const' array?

前端 未结 4 900
旧巷少年郎
旧巷少年郎 2021-01-19 07:53

In a C module (aka, compilation unit), I want to have some private data, but expose it read-only to the outside world. I achieve that by having a field in a s

4条回答
  •  遥遥无期
    2021-01-19 08:24

    pointer to array not compatible to a pointer to 'const' array?

    Yes they are incompatible, you can't change a nested const qualifier, int (*a)[42] is not compatible with int const (*b)[42] related, as double ** is not compatible with double const **

    Is my assumption correct that this doesn't lead to a hole in const correctness?

    Well, you are adding const qualifier so no. In fact, return non const don't produce a warning and don't break const correctness according to the same rule that doesn't allow you to add const. But code like that are very confuse but are not undefined behavior.

    shape *fooshapes(const foo *f)
    {
        return f->shapes;
    }
    

    Does the explicit cast violate the standard here?

    Strictly, Yes, as compiler said there types are incompatibles, however I don't think it would produce a bug in any actual classic hardware.

    The thing is the standard don't guarantee that double *a and double const *b have the same size or even the same value but just guarantee that a == b will produce a positive value. You can promote any double * to double const * but like I said you must promote it. When you cast you don't promote anything because the array/pointer is nested. So it's undefined behavior.

    It's a "you simply can't do that in C", you could ask but "what I'm suppose to do ?". Well, I don't see the purpose of your structure neither of your pointer to array in the structure. To fix the deeper problem of your data structure, you should ask an other question where you talk more about what is your purpose with this code. For example, your function could do something like that:

    uint8_t const *fooshapes(const foo *f, size_t i)
    {
        return f->shapes[i];
    }
    

提交回复
热议问题