使用动态n生成1到n之间的数字int

jac*_*per 1 c

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

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

for(i = 0; i < n; i++) {
    output[i] = i;
}
Run Code Online (Sandbox Code Playgroud)

但是,由于n是动态的,代码将无法编译.

任何帮助将不胜感激 - 提前感谢.

Jon*_*art 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);
Run Code Online (Sandbox Code Playgroud)

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

完成数组后,需要取消分配内存free.