gpt4 book ai didi

c - 如何在 for 中创建 N 个变量?

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:18 24 4
gpt4 key购买 nike

我需要一些方法来通过 for 创建 N 个变量(数字大于 1)?
例如,类似的东西:

 int N=1000;   
for(int i=0; i < N; i++){
char* var_i = malloc(sizeof(1));
}

注意:我知道上面的代码不起作用,我写它只是为了解释我的意图。

最佳答案

你可以使用数组。这里有两个例子:

#include <stdio.h>
#define N 10000

int main(void)
{
char array[N];
for (size_t i = 0; i < N; i++) {
/* Do what you want. */
}
return 0;
}

或者如果你想在堆中:

#include <stdio.h>
#include <stdlib.h>
#define N 10000

int main(void)
{
char *array = malloc(sizeof *array * N);
if (array == NULL) {
perror("Malloc");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < N; i++) {
/* Do what you want. */
}
free(array);
return 0;
}

关于c - 如何在 for 中创建 N 个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44374394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com