我绝对是 C 游戏的新手,希望对以下代码片段有所帮助:
#include <stdio.h>
int main() {
int cases;
scanf("%d", &cases);
printf("%d", cases);
int i;
int *heights;
for(i=0; i<cases; i++){
scanf("%d", &heights[i]);
}
return 0;
}
我知道这是段错误,因为我给 scanf
一个 NULL
指针,所以有什么方法可以让 scanf
提供值进入这个指针?或者是否有更好的方法从 stdin
获取可变数量的参数,而我完全没有看到?
最佳答案
使用malloc
为 heights
动态分配空间。
int *heights = malloc(cases*sizeof(int));
当您完成 heights
时,通过调用 free(heights)
来释放 指针。
对于小值的cases
,你可以使用variable length arrays :
int heights[cases];
并且不要忘记在 C99 模式下编译您的代码 (-std=c99
)。
关于c - 使用指针代替数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24301798/