警告 C4090:“function":不同的“const"限定符 [英] warning C4090: 'function' : different 'const' qualifiers

查看:111
本文介绍了警告 C4090:“function":不同的“const"限定符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下代码行,我观察到错误警告 C4090:'function':不同的 'const' 限定符".通过其他类似的问题,所以我理解(不是 100%)这是因为

I am observing error "warning C4090: 'function' : different 'const' qualifiers " because of below line of code. Going through other similar questions on SO I understand (not 100 percent) it is because of

--> const char* EmployeeList[] 和我在 EmployeeList 的 qsort 中的声明

--> const char* EmployeeList[] and my declaration in qsort of EmployeeList

    #define Elements(array) (sizeof(array)/sizeof((array)[0]))

   const char *EmployeeList[] =
   {
      "Larry Page", "Sergy Brin", "Sundar Pichai", "Merrisa Mayer"
   };

// called from main
SortEmployee(EmployeeList, Elements(EmployeeList));

int Compare(const void *elemA, const void *elemB)
{
 ...
}

void SortEmployee(const char *EmployeeList[], size_t EmployeeCount)
{
    qsort(EmployeeList, EmployeeCount, sizeof(EmployeeList[0]), Compare);
}

但是我无法解决它-任何指针如何为字符串数组执行此操作.

However I am unable to resolve it- Any pointers how to do it for array of strings.

推荐答案

问题是 qsort does not 将其参数声明为 const,而您的代码可以.这意味着 qsort 可以(理论上)改变 EmployeeList 指向的数据.因此,编译器会报告此错误.

The problem is qsort does not declare its argument as const, while your code does. That means qsort may (in theory) change data, pointed by EmployeeList. So, the compiler reports this error.

这是官方示例:https://msdn.microsoft.com/en-us/library/k77bkb8d.aspx

然而,这里有一个简单的版本来演示我的想法:

How ever, here is a simple version to demonstrate my idea:

void foo(char* a) {
   *a = '1'; // I got pointer to char, and changed this char!
}


int main() {
   const char *a = "A"; // I have "CONSTANT POINTER": it points to CONSTANT memory, that CAN NOT be changed (by the way, string constants can't in many environments).
   foo(a); // I pass it to my function, that will change it.
   return 0;
}

映像您的编译器将 a 存储在只读内存中(它可以,因为我们告诉它这是一个指向只读数据的指针").然后修改它(在 main 函数中).可能会发生一些不好的事情.因此,编译器会警告您嘿,您将一个指向 常量 数据的指针传递给某个函数,该函数不知道该数据是常量并且可能em> 改变它"

Image your compiler stores a in read-only memory (It can, because we told it "this is a pointer to READ ONLY data"). You then modify it (in main function). Something bad may happen. So, the compiler warns you "hey, you pass a pointer to constant data to some function, that does not know that this data is constant and may change it"

这篇关于警告 C4090:“function":不同的“const"限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆