Re: [問題] c how to program P.274~275宣告的pointer方式
※ 引述《ooww (亞古獸)》之銘言:
: (第一次發問,請鞭小力一點)
: 1. const int *ptr;
: 2. int * const ptr;
: 3. const int *const ptr;
: 這三個宣告差在哪裡?
: 第1個我了解,
: 第3個的" * "跟const貼在一起是什麼意思?
第2個---ptr是個常數指標,指到一個int
第3個---ptr是個常數指標,指到一個常數int
我測試的結果 , "常數"的意義是無法"直接"assign給此變數 即使assign的是同一值
但是"間接"assign可以
以下是測試的code VS2005編譯的
#include "stdio.h"
#include "conio.h"
int main(void)
{
int x = 5 , y = 10;
const int *ptr1; // ptr1是個指標,指到一個常數int
int *const ptr2 = &x; // ptr2是個常數指標,指到一個int
const int *const ptr3 = &y; // ptr3是個常數指標,指到一個常數int
int **ptr_breaker; // 搞破壞用的指向int *的指標
// 1st example
ptr1 = &x;
printf("%d\n",*ptr1);
// *ptr1 = *ptr1; // 這一行編譯會出錯 , 即使assign的是同一值
x = 6;
printf("%d\n",*ptr1); // 但如果是經由x間接改變 就不會出錯
// 2nd example
// ptr2 = &x; // 這一行編譯也會出錯 , 即使assign的是同一值
printf("%d,%d\n",*ptr2, (int)ptr2);
// 3rd example
// ptr3 = ptr3;
// *ptr3 = &y; // 這兩行編譯也會出錯
printf("%d,%d\n",*ptr3,(int)ptr3);
ptr_breaker = (int **)(&ptr3);
*ptr_breaker = &x;
printf("%d,%d\n",*ptr3,(int)ptr3); // 惡搞過後 , ptr3指向的值與儲存的
// 位址都被改變
getch();
return 0;
}
感覺上 如果真的要宣告為const的話 還不如用#define
比較不容易在開發中出錯
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.138.161.236
→
01/09 10:47, , 1F
01/09 10:47, 1F
→
01/09 10:53, , 2F
01/09 10:53, 2F
推
01/09 11:29, , 3F
01/09 11:29, 3F
推
01/09 16:18, , 4F
01/09 16:18, 4F
→
01/09 16:18, , 5F
01/09 16:18, 5F
推
01/09 16:40, , 6F
01/09 16:40, 6F
推
01/10 01:45, , 7F
01/10 01:45, 7F
→
01/10 01:45, , 8F
01/10 01:45, 8F
推
01/10 01:49, , 9F
01/10 01:49, 9F
→
01/10 01:50, , 10F
01/10 01:50, 10F
→
01/10 01:52, , 11F
01/10 01:52, 11F
推
01/10 01:57, , 12F
01/10 01:57, 12F
→
01/10 01:57, , 13F
01/10 01:57, 13F
→
01/10 01:58, , 14F
01/10 01:58, 14F
→
01/10 22:20, , 15F
01/10 22:20, 15F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):