(原創) 如何確保傳進function的array不被任意更改? (C/C++) (C)
我們知道array是以pointer的形式傳進function後,pointer是以copy by value的方式傳進去,可以任意更改不會影響到原來的array,但對於array而言,卻是by adress的方式,可以透過此pointer去更改原來array內的值,該如何確保function不去更改原來array內的值呢?
1
/*
2
(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4
Filename : ArrayPassToFunctionConst.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to pass array to function by const
7
Release : 02/08/2007 1.0
8
*/
9
10
#include <iostream>
11
12
using namespace std;
13
14
void func(const int *pia, const int size) {
15
for(int i = 0; i != size; ++i) {
16
cout << pia[i] << endl;
17
}
18
}
19
20
int main() {
21
int ia[] = {0, 1, 2};
22
func(ia, 2);
23
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

只要如14行在int *pia前面加上const即可,compiler就可以幫你檢查是否function是否更改了array內的值。
在C#並無法如這樣加上const,compiler無法過。