将for循环中的值存储到数组中

fcl*_*pez 1 c arrays for-loop

我想将从for-loop读取的值存储到数组中

char A[];
int x;
int y=5;

for( int i=0; int i =1000; i++) {
   x = x+y;
   // then store/append x as elements of the char array, A.... what is the syntax?
}
Run Code Online (Sandbox Code Playgroud)

Kei*_*ler 6

通过查看你的代码,我假设你正在尝试构建一个静态数组,所以我将证明这一点(所以你不必专注于像malloc这样的概念).但是,您的代码存在一些问题,我现在将讨论这些问题.

首先关闭你的数组声明:

char A[];
Run Code Online (Sandbox Code Playgroud)

对我来说,看起来你的for循环正在填充一个整数数组,所以这个数组应该被声明为一个整数,而且你没有设置数组的大小,因为你的代码已经增加,直到它为1000你应该只是声明一个包含1000个元素的整数数组:

int A[1000];
Run Code Online (Sandbox Code Playgroud)

第二个你的循环:

for(int i = 0, int i = 1000; i++)
Run Code Online (Sandbox Code Playgroud)

你最好只i用其余的变量来声明,尽管你可以在for循环中声明它,我个人不建议这样做.你i也在这个循环中声明了两次.最后你继续循环(i = 1000)的条件将立即中止循环i,1000因为你将它设置为永远不会等于0.在中间语句为真时,请记住仅循环for循环.所以考虑到这一点你现在应该:

int A[1000], i, x, y = 5;
for(i = 0; i < 1000; i++)
Run Code Online (Sandbox Code Playgroud)

现在我们可以使用=语句和值i来设置每个数组元素A:

int A[1000], i, x, y = 5;
for(i = 0; i < 1000; i++)
{
    x += y;
    A[i] = x;
}
Run Code Online (Sandbox Code Playgroud)

就这么简单!