Assigning a constant is not const in C

In the following:

struct adt { void * A; };

int new_adt(const void * const A)
{
    struct adt * r = malloc(sizeof(struct adt));
    r->A = A;
}

I get:

warning: assignment discards qualifiers from target pointer type


I know I can use

memcpy(&(r->A), &A, sizeof(void *));

to get around this, but I have to ask: is there an alternative?

Using const void * const, I pretend that no changes will be made to the input. Also, now that I'm thinking about it, that's const void *enough, isn't it? (Since I cannot change the pointer so that it affects the caller)

Thanks for taking the time to read.

+3
source share
3 answers

If you never want to change Athrough your pointer from adt, then you should also make this pointer const, i.e.:

struct adt {
    const void * A;
};

This will result in an error.

A adt, new_adt const.


: , :

const, , . , , . : const int * A int const * A (const int, ), int * const A , int.

: const-correctness. " " , , .

+5

const void * const, , .

, , , , , .

, .

+7

const:

r->A = (void *) A;

, , . , , "A" , , . , .

Imagine that “A” indicates the location in the data section of your binaries; trying to write to it, after you select const, most likely will call segfault.

So, think about what you are trying to do closer before trying to get around the compiler warning. They warn for a good reason.

0
source

Source: https://habr.com/ru/post/1791355/


All Articles