C – 当实际为 struct** 时,const 修饰符被丢弃。

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月2日 04:30:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定