我用 C 语言编写了一个函数,它从用户处获取 10 个整数并将其打印出来。
void memoryallocationtest(int number)
{
// allocate space for 10 integer
char *input = malloc( 32 * sizeof(char) );
long *x = malloc( number * sizeof(long) );
char *ptr;
printf("please enter 10 integer X consecutively, -2147483648 <= X <= 2147483647)\n");
/* promts user to enter ith integer
* converts input string to long value and saves result in x
*/
for(int i = 0; i < number; i++)
{
printf( "%i. Integer:", (i + 1) );
scanf( "%s", input );
x[i] = strtol( input, &ptr, 10 );
}
free(x);
free(input);
}
这是一种有效的方法吗?
有没有为我的字符数组“输入”分配和释放空间的点,或者我应该像 char input[32];
那样声明它?还是这就是隐含发生的事情?
最佳答案
为 10 个整数的数组静态预留内存是这样完成的(数据位于内存的堆栈部分。)
int array[10];
对于动态分配,数据位于堆上。
int *array = (int *) malloc(sizeof(int) * 10);
这是一个简单的图像,大致描述了典型程序的内存布局:
Is there any point of allocating and freeing space for my char-array "input" or should I just declare it like char input[32]; or is that what happens implicit anyway?
动态分配的优点是您无需提前知道要向操作系统请求多少内存。缺点是管理动态分配的内存比较困难,并且更容易受到external fragmentation的影响。 。当您使用 malloc 时,您所描述的不会隐式发生。
如果你事先知道你需要多少内存(你的整数数组到底有多长),就不需要使用动态分配(malloc),也不需要像“char input[32];”这样声明数组。是完全足够的。
关于c - 声明数组与为其分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616750/