在C / C ++未知大小数组初始化 [英] Initializing Arrays in C/C++ With Unknown Size

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

问题描述

我怎么能初始化C中的数组,如

How can I initialize an array in C such as

void initArr(int size)
{
  ...
}

C语言并没有给初始化数组的选项
如果他的大小不是一个恒定值,如果我初始化
一般为(int *改编;),所以它给了我的'改编'误差不
被初始化。

The C language does not give the option to initialize an array if his size is not an constant value, and if I initialize it generally (int *arr;) so it gives me error of 'arr' is not being initialized.

相若,我该怎么做,当我有维数组
大于1(基质,例如)?

Similarily, how can I do that when I have an array with dimension bigger than one (matrix, for example)?

推荐答案

这在C和C工作答案++是动态内存分配

The answer that works in C and C++ is dynamic memory allocation

int *arr = (int*)malloc(size*sizeof(int));

在C ++中,你会preFER使用,而不是新的malloc,但原理是一样的。

In C++ you would prefer to use new instead of malloc, but the principle is the same.

int* arr = new int[size];

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

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