C語言 常量指標

2021-10-10 07:48:29 字數 1708 閱讀 1858

最近想要用課餘時間刷一下演算法題,發現c語言的指標部分忘得差不多了,再加上原來就有好多細節不清楚,所以打算看《深入理解c指標》這本書重新學一遍。這篇文章爭取對常量指標的各種情況做乙個總結。

#include

intmain()

//只改變整數常量的值

num =

1;

test.c: in function

'main':

test.c:9:17: warning: initialization of 'const int *'

from

'int' makes pointer from integer without a cast [

-wint-conversion]

9 | const int *p = num;

| ^~~

test.c:12:6: error: assignment of read-only variable 'num'

12 | num = 1;

//只改變整數常量指標指向的整數

int*num1;

p =&num1;

test.c: in function

'main':

test.c:9:17: warning: initialization of 'const int *'

from

'int' makes pointer from integer without a cast [

-wint-conversion]

9 | const int *p = num;

| ^~~

test.c:17:4: warning: assignment to 'const int *'

from incompatible pointer type

'int **'

[-wincompatible-pointer-types]

17 | p = &num1;

| ^

前兩步只是測試常量的基本性質,那就是賦值後就無法被修改,值得注意的是常量可以在宣告時賦值,也可以在宣告後賦值。另外,就算第二次賦值的和第一次賦值的是同乙個值,也會出錯。

//整數常量

const

int num =0;

//整數常量指標

const

int*p = num;

num =

0;

test.c: in function

'main':

test.c:9:17: warning: initialization of 'const int *'

from

'int' makes pointer from integer without a cast [

-wint-conversion]

9 | const int *p = num;

| ^~~

test.c:11:6: error: assignment of read-only variable 'num'

11 | num = 0;

C語言和C 指標常量和常量指標

指標常量,用指標修飾的常量,它的本質是乙個常量 int a 111,b 222 int const p a printf p n p printf d n p p 333 printf d n p p b 報錯,p的值不能更改,error assignment of read only variab...

c語言之常量指標與指標常量

在c c 中用關鍵字const來定義乙個唯讀的變數和物件,它有如下的優點 1.fun const int var 不予許對傳入的引數進行修改,用於保護實參。2.有如有乙個巨集定義,或者類似於靜態變數,const int var2 1573,方便進行修改 3.節省記憶體,const定義只需占用一小塊記...

C語言之常量指標和指標常量

參考部落格 摘抄以上部落格內容 一 指標常量 1 首先是乙個常量,其次是用指標修飾的常量,一般表述為 int const p 指標常量2 指標指向的位置 位址 不能改變,指標本身是乙個常量,但是指標指向的內容 值 是可以發生改變的 3 通過 來進行演示如下 int a,b int const p a...