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

时间:2012-08-24 14:29:55

标签: 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?
}

4 个答案:

答案 0 :(得分:6)

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

首先关闭你的数组声明:

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

int A[1000];

第二个你的for循环:

for(int i = 0, int i = 1000; i++)

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

int A[1000], i, x, y = 5;
for(i = 0; i < 1000; i++)

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

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

就这么简单!

答案 1 :(得分:3)

您的代码存在多个问题

char A[1000]; // Need to specify a compile time constant for the array size
int x=0;
int y=5;

for( int i=0; i < 1000; i++) { // Condition was wrong
   x = x+y;
   // then store/append x as elements of the char array, A.... what is the syntax?
   A[i] = x; // Add the value
}

此外,char数据类型将无法保存超过特定大小的值,并且会导致溢出使值环绕。您可能希望将A声明为int A[1000]

  • 数组必须是常量,或者您需要使用malloc分配它们
  • 循环的第二部分无法再次重新声明i。如果你有一个赋值语句,它也将永远循环。我假设你想要循环到1000而不是
  • 要分配到数组中的实际问题是使用[]运算符。
  • x未初始化为任何内容,使其包含垃圾值。您需要在声明变量时为变量赋值。 C不会自动为您执行此操作。

答案 2 :(得分:2)

如果要在C中添加元素,可以使用多种方法。

静态数组

声明一个静态数组,其中包含许多您无法编辑的元素。如果您确切知道您将拥有的元素数量,那么它就是完美的。 @Dervall做得很好。

动态数组

使用malloc函数声明动态数组。尺寸可以改变。虽然这很难维护。但是:

int *A = NULL;
int *tmp; // to free ex allocated arrays
int i;
int j;
int x = 0;
int y = 5;

for (i = 0 ; i < 1000 ; i++) {
    // saving temporarly the ex array
    tmp = A;
    // we allocate a new array
    if ((A = malloc(sizeof(int) * (i + 1))) == NULL) {
        return EXIT_FAILURE;
    }
    // we fill the new array allocated with ex values which are in tmp
    for (j = 0; j < i; j++) {
        A[j] = tmp[j];
    }
    // if it's not the first time, we free the ex array
    if (tmp != NULL)
        free(tmp);
    x = x + y;
    A[i] = x;
}

最好将它分成一个函数当然:)

您也可以使用realloc功能!这是为此而做的,但我觉得像这样开发很有意思

答案 3 :(得分:0)

你的代码片段有很多问题。这是一个可编辑的例子

char *A = malloc(sizeof(*A) * NUM_ELEMENTS); // you shouldn't declare on the stack
int x = 0; // initialize
int y=5;

for( int i = 0; i < NUM_ELEMENTS; i++) { // proper for loop syntax
    x = x+y;
    A[i]=x; // assign element of array
}

更好的版本:

char *A = malloc(sizeof(*A) * NUM_ELEMENTS);

for (int i = 0; i < NUM_ELEMENTS; ++i)
    A[i] = 5 * i;
相关问题