(原創) 如何確保傳進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
 4Filename    : ArrayPassToFunctionConst.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to pass array to function by const
 7Release     : 02/08/2007 1.0
 8*/

 9
10#include <iostream>
11
12using namespace std;
13
14void func(const int *pia, const int size) {
15  for(int i = 0; i != size; ++i) {
16    cout << pia[i] << endl;
17  }

18}

19
20int main() {
21  int ia[] = {012};
22  func(ia, 2);
23}


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

在C#並無法如這樣加上const,compiler無法過。

posted on 2007-02-08 16:02  真 OO无双  阅读(691)  评论(0编辑  收藏  举报

导航