1

我正在努力使用一种算法将 1 和动态变量 n 之间的数字打印到 int 中。

int n = // dynamic value
int i = 0;
int output[n];

for(i = 0; i < n; i++) {
    output[i] = i;
}

但是,由于 n 是动态的,因此代码不会编译。

任何帮助将不胜感激 - 在此先感谢。

4

3 回答 3

10

您需要分配一个缓冲区或动态大小的数组,其中malloc

int n = // whatever
int i = 0;
int* output = NULL;

// Allocate the buffer
output = malloc(n * sizeof(int));
if (!output) {
    fprintf(stderr, "Failed to allocate.\n");
    exit(1);
}

// Do the work with the array
for(i = 0; i < n; i++) {
    output[i] = i;
}

// Finished with the array
free(output);

output是指向您分配的缓冲区开头的指针,您可以将其视为n ints.

完成数组后,您需要使用free.

于 2012-12-27T18:06:54.267 回答
0

这应该有效:

int n = // whatever
int i = 0;
int* output = (int*)malloc(sizeof(int)*n);

for(i = 0; i < n; i++) {
    output[i] = i;
}

free(output);当你不再需要它时不要忘记。

编辑:做到了C。

于 2012-12-27T18:07:47.107 回答
0

如果“n”在运行时发生变化,那么您可以像评论中建议的那样使用 malloc。然后检查是否需要更多空间,然后在需要时自动重新分配更多空间

于 2012-12-27T19:26:23.023 回答