How to initialize an array in C

来源:互联网 发布:阿里云dns没有百度稳定 编辑:程序博客网 时间:2024/05/18 03:56

If your compiler is GCC you can use following syntax:

int array[1024]={[0 ... 1023]=5};

Check out detailed description: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html

 

#include <stdio.h>#include <stdlib.h>intmain(){    int i = 0;    int array[100] = { [0 ... 99] = 5};     for (i = 0; i < 100; i++) {        printf("array[%d] = %d\n", i, array[i]);    }           return 0;}

 

轉載自 http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c

Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.

Don't overlook the obvious solution, though:

int myArray[10]={5,5,5,5,5,5,5,5,5,5};

Elements with missing values will be initialized to 0:

int myArray[10]={1,2};//initialize to 1,2,0,0,0...

So this will initialize all elements to 0:

int myArray[10]={0};//all elements 0

In C++, an empty initialization list will also initialize every element to 0:

int myArray[10]={};//all elements 0 in C++

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

staticint myArray[10];//all elements 0

And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)

0 0
原创粉丝点击