加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 哪种方式更适合阵列访问?

发布时间:2020-12-16 10:53:28 所属栏目:百科 来源:网络整理
导读:我有一个函数,我使用一个常量数组: void function(int Id){int array1[4] = {4 constants};int array2[4] = {4 constants}; for(int i=0; i4; i++){ //accessing the array 12 for computation; }} 将有近百万次从main()访问void函数(int Id). 我的问题是,
我有一个函数,我使用一个常量数组:

void function(int Id){
int array1[4] = {4 constants};
int array2[4] = {4 constants};
   for(int i=0; i<4; i++){
   //accessing the array 1&2 for computation;
   }
}

将有近百万次从main()访问void函数(int Id).

我的问题是,在头文件中声明array1和array2以及在function()内部访问是否更好,或者现在是否可以动态声明它们?

哪种方式会更快(考虑从头文件访问或动态声明)?

编辑:只能访问数组,并且不会在function()中修改数组.

解决方法

如果数组不会改变,并且不会在另一个函数中重用,那么最好将它们设置为静态.这避免了在每次调用函数时都需要在堆栈上构造数组.

void function(int Id){
    static const int array1[4] = {4 constants};
    static const int array2[4] = {4 constants};
    for(int i=0; i<4; i++){
        //accessing the array 1&2 for computation;
   }
}

编辑添加最好避免在数组声明和循环表达式中使用“幻数”4.如果没有这样做,很容易改变数组大小,忘记更改循环表达式.这可以通过使数组大小为常量,或者在循环表达式中使用sizeof()来完成,如此堆栈溢出问题所示:How do I determine the size of my array in C?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读