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

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

问题描述

有没有办法在 C 中先声明然后初始化数组?

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....};

但我需要做这样的事情

int myArray[SIZE];

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

推荐答案

在 C99 中,您可以使用复合字面量和 memcpy

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).

在 C89/90 中,您可以通过声明一个额外的源"数组来模拟这一点

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天全站免登陆