我需要在C全局数组由用户输入的大小 [英] I need to make a global array in C with a size inputted by the user

查看:100
本文介绍了我需要在C全局数组由用户输入的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要做一个全局变量在C,它是一个数组。阵列将[n]的[22] [N + 1],其中n可以是3,4,5或6,并且由用户选择

有没有办法做到这一点,或者我应该只是做数组[6] [22] [7],并有功能处理它只能使用部分组成为n(如果让任何意义)<? / p>

我已经为计算机科学课前做到这一点,但不记得究竟是如何做到这一点。


解决方案

对于数组小(当然,假设合理规模的数据类型),你可能只是会更好使 [6] [ 22] [7]你在你的问题提配置 - 它不喜欢你要浪费那么多的空间。不幸的是你,C99变长数组没有为全球数组。这意味着,你唯一的选择是动态分配使用的malloc() / 免费()

Basically I need to make a global variable in C that is an array. The Array will be [n][22][n+1] where n is either 3,4,5 or 6 and is selected by the user.

Is there a way to do this or should I just make the array [6][22][7], and have the functions dealing with it only use the parts up to n (if that makes any sense)?

I've had to do this before for a computer science class but can't remember exactly how to do it.

解决方案

For an array that small (well, assuming reasonably sized data types), you might just be better off making the [6][22][7] allocation you mention in your question - it's not like you're going to waste that much space. Unfortunately for you, C99 variable length arrays don't work for global arrays. That means your only other option is dynamic allocation using malloc()/free().

这篇关于我需要在C全局数组由用户输入的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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