C语言的数组学习入门之对数组初始化的操作

2020-01-06 14:10:15于丽

假设给一二维数组初始化,将数组的每个元素都初始化为0

方法有两种:

1)使用循环逐个的把数组的元素赋值为0;

2)使用内存操作函数memset将数组所占的内存内容设置为0;

测试代码如下:


#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>

#define     K    15
#define     DIM   10
#define     LOOP  1000000

int main(int argc, char** argv)
{
    double     o_centers[K*DIM];
    int       i = 0, j = 0, k = 0;


    MPI_Init(&argc, &argv);

    printf("Start to test array assign...n");
    double     starttime1 = MPI_Wtime();
    for(k = 0; k < LOOP; k++)
        for(i = 0; i < K; i++)
            for(j = 0; j < DIM; j++)
                o_centers[j + i*DIM] = 0;
    double     endtime1 = MPI_Wtime();
    printf("Array assign takes %5.12f seconds...n", endtime1 - starttime1);


    printf("Start to test memset assign...n");
    double     starttime2 = MPI_Wtime();
    for(k = 0; k < LOOP; k++)
        memset(o_centers, 0, K*DIM*sizeof(double));
    double     endtime2 = MPI_Wtime();
    printf("Memset assign takes %5.12f seconds...n", endtime2 - starttime2);

    MPI_Finalize();
    return 0;
}

编译运行后,得到结果:


Start to test array assign...
Array assign takes 0.624787092209 seconds...
Start to test memset assign...
Memset assign takes 0.052299976349 seconds...

补充说明

如果数组定义的时候没有指定其大小,并且初始化采用了列表初始化,那么数组的大小由初始化时列表元素个数决定。所以上面例子中的数组分别为 int[4] 和char[4]类型。如果明确指定了数组大小,当在初始化时指定的元素个数超过这个大小就会产生错误。

如果初始化时指定的的元素个数比数组大小少,剩下的元素都回被初始化为0。例如:


int arr[8]={1,2,3,4};

等价于


int arr[8]={1,2,3,4,0,0,0,0};

字符数组可以方便地采用字符串直接初始化。

C的字符串,也很简单,它也是一个数组,只不过最后一个元素是'nul',加了这么一点限制之后,字符串自然就失去了数组的分形强悍,但C的字符串依然不可小看,因为字符串中,只要带上了'nul',都能看成是字符串,好比,”hello”这条字符串,只要改变起始地址,就可轻而易举地得到”ello”,”llo”,”lo”,”o”这好几条子字符串,这个特点,可以简化很多字符串操作,并且效率最高。此外,C字符串,只要你愿意,完成可以拿来当成是字符数组来使用,这样,就又恢复了数组分形功能,C函数库中和WINDOWS API,有很多函数就是专门处理C字符数组的。