[英]Why can I not assign a const pointer to a const pointer in a struct?
[英]Why can I modify the const pointer in C?
今天我嘗試使用const標識符,但我發現const變量仍然可以修改,這讓我感到困惑。
以下是代碼,在compare(const void * a,const void * b)函數中,我試圖修改a指向的值:
#include <stdio.h>
#include <stdlib.h>
int values[] = {40, 10, 100, 90, 20, 25};
int compare (const void *a, const void*b)
{
*(int*)a=2;
/* Then the value that a points to will be changed! */
return ( *(int*)a - *(int*)b);
}
int main ()
{
int n;
qsort(values, 6, sizeof(int), compare);
for (n = 0; n < 6; n++)
printf("%d ", values[n]);
return 0;
}
然后我也試圖改變自身的價值:
#include <stdio.h>
#include <stdlib.h>
int values[] = {40, 10, 100, 90, 20, 25};
int compare (const void *a, const void*b)
{
a=b;
return ( *(int*)a - *(int*)b);
}
int main ()
{
int n;
qsort(values, 6, sizeof(int), compare);
for (n = 0; n < 6; n++)
printf("%d ", values[n]);
return 0;
}
但是,我發現它們都有效。任何人都可以向我解釋為什么我需要在比較參數列表中使用const,如果它們仍然可以更改?
它只適用於這種情況,因為你正在使用的指針最初不是常數。 拋棄const然后修改值是未定義的行為。 UB意味着應用程序可以做任何事情,從成功到崩潰,讓紫色的龍飛出你的鼻孔。
它保護你免受愚蠢的錯誤,而不是當你努力犯錯時。
(int *)a
當a
是const something *
是一種不好的做法,請改用(const int *)a
。
a = b
當a
是const void *
是好的,因為只有指向的值是const。 如果你想要*a = x
和a = x
不允許,請聲明a
const void * const
。
情況1:您正在使用靜態強制轉換來拋棄常量。 您違反了為該方法定義的合同。
情況2:您沒有更改a的內容(這是const),而是分配包含const void指針的變量a。
對於實際意義:對於案例1.)你可以用腳射擊自己,以防萬一沒有真正指向一個變量。
建議:只有在你知道自己在做什么的情況下才能拋棄常量。
其實。
int compare (const void *a, const void*b);
這里有兩件事你需要考慮,指針和指針所指向的內存位置。 指針不是常量,而是內存位置。
如果要將簽名更改為:
int compare (const void *const a, const void *const void);
那么一切都將是const。 在您的情況下,您可以更改指針,但不能更改值。 這樣你的指針就可以指向不同的內存位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.