现在的位置: 首页 > 综合 > 正文

数组的初始化方法大全

2013年07月23日 ⁄ 综合 ⁄ 共 635字 ⁄ 字号 评论关闭

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

对于数组,有以下几个原则:

int main(int argc, char *argv[])
{
    char a[10] = {'\0'};    //{0, ..., 0}  第1个为0,后面的0为系统自动补的,所以这种行为可以用来进行字符串的初始化
    int b[10] = {1, 2, 3,}; //{1, 2, 3, 0, ..., 0} 后面7个0为系统自动补的
    int c[10];
    memset(c, 0, sizeof(int) * 10); //{0, ..., 0}
    int d[10] = {3}; // {3, 0, ..., 0}

    int m[][3] = {{1, 2, 3}, {4, 5, 6}};
    //int k[][] = {{1, 2, 3}, {4, 5, 6}}; error: multidimensional array must have bounds for all dimensions except the first
    int n[][3] = {{1, 2, 3}, {4}};  //{{1, 2, 3}, {4, 0, 0}}
    int g[][3] = {{1, 2, 3}, {4, 5}}; //{{1, 2, 3}, {4, 5, 0}}
    int h[2][2] = {{1, 2}}; //{{1, 2}, {0, 0}}
    int k[2][2] = {{1}}; //{{1, 0}, {0, 0}}
    return 0;
}

当然还漏了一种,用for循环进行初始化啦。

抱歉!评论已关闭.