英文:
C - const qualifier discard when const void* is actually struct**
问题
在代码中遇到的问题是:"cast discards 'const' qualifier",也就是“强制转换丢弃了 'const' 限定符”。您想知道如何正确地从 const void *
中进行解引用,如果该指针实际上是指向结构体的指针。
以下是您的代码的翻译部分:
int cmp_str_and_dirent(const void *key, const void *elem) {
const char *name = key;
const struct dirent *de = *(const struct dirent**)elem;
^ 强制转换丢弃了 `const` 限定符
return strcmp(name, de->d_name);
}
struct dirent **entries;
file_count = scandir(path, &entres, NULL, alphasort);
struct dirent *found = bsearch(name, entries, file_count,
sizeof(struct dirent*), cmp_str_and_dirent);
请注意,代码中的错误是在强制类型转换中丢弃了 const
限定符,这可能会导致潜在的问题。如果您需要解决这个问题,您可能需要重新考虑如何处理 const
限定符以确保代码的正确性。
英文:
Stuck on "cast discards 'const' qualifier"
I have a code:
int cmp_str_and_dirent(const void *key, const void *elem) {
const char *name = key;
const struct dirent *de = *(const struct dirent**)elem;
^ Cast discards `const` qualifier
return strcmp(name, de->d_name);
}
struct dirent **entries;
file_count = scandir(path, &entres, NULL, alphasort);
struct dirent *found = bsearch(name, entries, file_count,
sizeof(struct dirent*), cmp_str_and_dirent);
So the question is: How to properly do dereferencing from const void *
if that pointer is actually pointer to a pointer to a structure?
compiler gcc 11.2.1, using -std=gnu11
答案1
得分: 0
尽管C允许在类型名称之前放置诸如const
之类的类型限定符,以便使它们的用法看起来类似于register
之类的存储类,但当它们用于指针声明时,这会使它们的含义变得模糊。尽管register int *p
会声明一个具有register
存储类的指向int
的指针,但定义const int *q
则定义了一个指向const int
的非const指针。将const
限定符放在类型名称之后,并认识到它们相对于星号的位置很重要,一切将变得清晰。我认为你想要的是将指针转换为(struct dirent const * const *)
,即指向只读指针的指针,指向只读对象。
英文:
Although C allows type qualifiers such as const
to be placed before type names so as to allow their usage to appear similar to storage classes such as register
, this obscures their meaning when they are used in pointer declarations. Although register int *p
would declare a pointer with register
storage class that identifies an int
, the definition const int *q
defines a non-const pointer to a const int
. Move const
qualifiers after the type name, and recognize that their placement relative to asterisks is significant, and all will become clear. I think what you want is to convert the pointer to a (struct dirent const * const *)
, i.e. a pointer to a read-only pointer to a read-only object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论