How to initialize all members of an array to the same value?

后端 未结 23 1845
清歌不尽
清歌不尽 2020-11-21 04:34

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I

23条回答
  •  清歌不尽
    2020-11-21 05:22

    If you mean in parallel, I think the comma operator when used in conjunction with an expression can do that:

    a[1]=1, a[2]=2, ..., a[indexSize]; 
    

    or if you mean in a single construct, you could do that in a for loop:

    for(int index = 0, value = 10; index < sizeof(array)/sizeof(array[0]); index++, value--)
      array[index] = index;
    

    //Note the comma operator in an arguments list is not the parallel operator described above;

    You can initialize an array decleration:

    array[] = {1, 2, 3, 4, 5};
    

    You can make a call to malloc/calloc/sbrk/alloca/etc to allocate a fixed region of storage to an object:

    int *array = malloc(sizeof(int)*numberOfListElements/Indexes);
    

    and access the members by:

    *(array + index)
    

    Etc.

提交回复
热议问题