[英]qsort const pointer problems
char **av;
SIZE_T ac;
char WordCopy[256] = {0};
av[ac] = strdup(p);
qsort(av, ac, sizeof (char *), compare);
STATIC int compare(const void *p1, const void *p2)
{
const char *pp1 = *(const char **)p1;
const char *pp2 = *(const char **)p2;
return strcmp(pp1, pp2);
}
But, it gives me the following error: 但是,它给了我以下错误:
complete.c: In function ‘compare’:
complete.c:26:24: error: cast discards ‘__attribute__((const))’ qualifier from pointer target type [-Werror=cast-qual]
const char *pp1 = *(const char **)p1;
^
complete.c:27:24: error: cast discards ‘__attribute__((const))’ qualifier from pointer target type [-Werror=cast-qual]
const char *pp2 = *(const char **)p2;
^
The old way it was written, works: 它的旧编写方式有效:
STATIC int
compare(p1, p2)
CONST char **p1;
CONST char **p2;
{
return strcmp(*p1, *p2);
}
I don't understand what the difference is... why am I getting the casting error? 我不知道有什么区别...为什么会出现投放错误? I found a few other similar-lokking issues here, which seemed to suggest that the syntax I am using should work... but it clearly does not.
我在这里发现了其他一些类似的问题,这似乎表明我使用的语法应该可以工作……但是显然不行。
I'd rather do it "properly" and not just disable the warning (disabling warnings will not pass code review). 我宁愿“适当地”执行此操作,而不仅仅是禁用警告(禁用警告不会通过代码审查)。
EDIT : User chux asked what happened if I set a new var.. here is the result: 编辑 :用户chux问如果我设置一个新的变量会发生什么。这是结果:
const char **s1 = (const char **)p1;
Produces: 产生:
complete.c: In function ‘compare’:
complete.c:26:23: error: cast discards ‘__attribute__((const))’ qualifier from pointer target type [-Werror=cast-qual]
const char **s1 = (const char **)p1;
^
You need to make what the pointer points to const
as well: 您还需要使指针指向
const
:
const char *pp1 = *(const char * const *)p1;
const char *pp2 = *(const char * const *)p2;
A solution should not need any cast. 解决方案不需要任何强制类型转换。
Examples of assigning a const void *
分配
const void *
示例
const void *p1 = NULL;
char *q1 = p1; // warning: initialization discards 'const' qualifier from pointer target type
const char *q2 = p1;
const char **q3 = p1; // warning: initialization discards 'const' qualifier from pointer target type
const char * const *q4 = p1;
char * const *q5 = p1;
const void *p1
points to const
data. const void *p1
指向const
数据。 The assignment target type needs to also be to a type that points to const
data. 分配目标类型也必须是指向
const
数据的类型。 q1
and q3
above do not point to const
data. 上面的
q1
和q3
不指向const
数据。 Either q4,q5
will work for OP's compare. q4,q5
用于OP的比较。
int compare5(const void *p1, const void *p2) {
char * const *pp1 = p1;
char * const *pp2 = p2;
return strcmp(*pp1, *pp2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.