如何写一个数值未知的数组,然后打印数字? [英] How write an array with unknown number of values, and then print the numbers ?
问题描述
所以我想知道我是否可以创建一个数组,我可以输入它我想要多少个数字,然后我想打印数字,所以我可以稍后使用它们来查找每个数字被重新计算的次数。 ..(对不起我的英文:/)
我的尝试:
#include< stdio.h>
#include< >
(我仍然不知道是否可以通过数组执行此操作:|)
如果你想要一个动态大小的数组,你应该查看方法malloc()
和calloc()
在< stdlib.h>中定义。 和< malloc.h>
但是,这两种方法都需要初始化时已知大小,所以如果你需要扩展你的数组,realloc()
会很有用。
你可以从一个固定长度的数组开始,然后先编写其余的代码,比如重复的查找程序和打印功能,然后在你完成所有工作时切换到动态数组。
int fixed_length [ 10 ];
// 为10个整数分配内存
int * dynamic_length =( int *)calloc( 10 , sizeof ( int ));
// 为10个整数分配空间
dynamic_length = ( int *)realloc(dynamic_length, 10 * sizeof ( int ));
// 使用后别忘了释放内存
free(dynamic_length);
so i want to know if i can make an array that i can enter to it how many numbers i want, then i want to print the numbers,so i can use them later to find how many times each number was reapeted ...(sorry for my english :/ )
What I have tried:
#include<stdio.h>
#include< >
(i still don't know if it is possible to do this with array :| )
If you want an array of dynamic size you should look into the methodsmalloc()
andcalloc()
defined in<stdlib.h> and <malloc.h>
However, both these methods require a known size at initialization, so if you need to expand your array,realloc()
would be useful.
You could start with a fixed length array and write the rest of your code first, like the duplicate finder and print function, and then switch to a dynamic array when you have every thing working.
int fixed_length[10]; // Allocates memory for 10 integers int* dynamic_length = (int*)calloc(10, sizeof(int)); // Allocate space for 10 mor integers dynamic_length = (int*)realloc(dynamic_length, 10 * sizeof(int)); // Don't forget to free the memory after usage free(dynamic_length);
这篇关于如何写一个数值未知的数组,然后打印数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!