变量数组声明 [英] Variable array declaration

查看:87
本文介绍了变量数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下C代码:

#include<stdio.h>
int main()
{int n,i;
scanf("%d",&n); 
int a[n]; //Why doesn't compiler give an error here?
}

当编译器最初不知道时如何声明数组?

How can I declare an array when the compiler doesn't know initially?

推荐答案

当直到编译时才知道数组的确切大小时,需要使用动态内存分配。在C标准库中,有用于动态内存分配的函数:malloc,realloc,calloc和free。

When the the exact size of array is unknown until compile time, you need to use dynamic memory allocation. In the C standard library, there are functions for dynamic memory allocation: malloc, realloc, calloc and free.

这些函数可以在中找到。 < stdlib.h> 头文件。

These functions can be found in the <stdlib.h> header file.

如果要创建数组,请执行以下操作:

If you want to create an array you do:

int array[10];

在动态内存分配中,您可以执行以下操作:

In dynamic memory allocation you do:

int *array = malloc(10 * sizeof(int));

您的情况是:

int *array = malloc(n * sizeof(int));

如果您分配了内存位置,请不要忘记取消分配:

If you allocate a memory position, never forget to deallocate:

if(array != NULL)
  free(array);

内存分配是一个复杂的主题,我建议您搜索该主题,因为我的回答很简单。您可以从以下链接开始:

Memory allocation is a complex subject, I suggest you search for the subject because my answer was simple. You can start with this link:

https://www.programiz.com/c-programming/c-dynamic-memory-allocation

这篇关于变量数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆