用C声明和初始化数组 [英] Declaring and initializing arrays in C

查看:201
本文介绍了用C声明和初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有先申报,然后用C初始化数组?一个办法

到目前为止,我一直在初始化数组是这样的:

  INT myArray的[SIZE] = {1,2,3,4,...};

但我需要做这样的事情。

  INT myArray的[SIZE]myArray的= {1,2,3,4,...};


解决方案

在C99可以组合使用复合字面常量与的memcpy

 的memcpy(myarray中,(INT []){1,2,3,4},sizeof的myArray的);

(假定源的尺寸和目标的大小是相同的)。

在C89 / 90,你可以模仿通过声明一个额外的源阵列

  const int的SOURCE [SIZE] = {1,2,3,4}; / *也许`static`? * /
INT myArray的[SIZE]
...
的memcpy(myArray的,来源,sizeof的myArray的);

Is there a way to declare first and then initialize an array in C?

So far I have been initializing an array like this:

int myArray[SIZE] = {1,2,3,4....};

But I need to do something like this

int myArray[SIZE];

myArray = {1,2,3,4....};

解决方案

In C99 you can do it using a compound literal in combination with memcpy

memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);

(assuming that the size of the source and the size of the target is the same).

In C89/90 you can emulate that by declaring an additional "source" array

const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
int myArray[SIZE];
...
memcpy(myarray, SOURCE, sizeof myarray);

这篇关于用C声明和初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆