在C ++中使用for循环初始化一系列数组 [英] Initializing series of arrays with for loops at C++

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

问题描述

我尝试使用for循环创建一系列多维数组。用户应输入要初始化的数组数。我想要这样的东西:

I try to create series of multidimensional arrays with for loops. User should input the number of arrays to be initialized. I want something like this:

int i;
printf("Enter the number of arrays you want: ");
scanf("%d",i)
for(int j=0;j<i;j++){
     long double x(j)[size][size];
}

如果我输入5,我想拥有x0,x1,x2,x3和x4。

if I input 5, I want to have x0, x1, x2, x3 and x4.

有可能吗?

谢谢您的帮助。

最好的问候,
Emre。

Best Regards, Emre.

推荐答案

编辑:刚注意到您正在使用C ++。在这种情况下,std :: vector绝对是最方便的解决方案。如果您对如何使用C风格的普通数组感到好奇,请继续阅读...

Edit: Just noticed you are using C++. In this case, std::vector is definitely the most convenient solution. If you are curious about how to do this with plain arrays, C style, then read on...

您可以不要这样您需要做的是创建一个3维数组(或2维数组,具体取决于您的观点...)

You can't do it like this. What you need to do is create a 3 dimensional array (or an array of 2-dimensional arrays, depending on your point of view...)

在C的情况下,内存分配很麻烦...您可以静态分配:

As is always the case with C, memory allocation is a pain... You can statically allocate:

long double x[N][size][size];

(N是在编译时确定的。请确保它足够大。
也如果N确实很大,则可以声明数组(可以作为全局变量,也可以使用 static 关键字)。否则,可能会导致堆栈溢出。)

(N is determined at compile time. Make sure you have it large enough. Also if N is really big, declare the array stactically (either as a global variable or with the static keyword). If you don't you can get a stack-overflow.)

或者您可以使用动态内存分配:

Or you can use dynamic memory allocation:

long double (*x)[size][size]; // x is a pointer to size by size arrays
x = malloc(n * sizeof(*x));
//You can now use x[j][a][b]...

也许使用typedef看起来会更好(即使我不是100%肯定在上一个示例中也得到了数组声明...):

Maybe things look better with a typedef (even I am not 100% sure I got that array ceclaration right in the last example...):

typedef long double typename_here[size][size];
typename_here *x;
x = malloc(n * sizeof(typename_here);






顺便说一句,您当前的代码不起作用的原因是


BTW, the reason your current code doesn't work is


  1. x(j)语法是虚构的:)

  2. 在循环内声明的变量在该块的内部。这意味着您不能在循环正文之后访问它们。

  1. The x(j) syntax is ficticious :)
  2. Variables declared inside a loop are internal to that block. This means you can't access them after the loop body.

这篇关于在C ++中使用for循环初始化一系列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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