用c语言声明数组而没有初始大小

ViS*_*STA 14 c arrays function

编写一个程序来操纵温度细节,如下所示.
- 输入要计算的天数.- 主要功能
- 以摄氏度输入温度 - 输入功能
- 将温度从摄氏度转换为
华氏度. - 单独功能- 查找华氏温度的平均温度.

如何在没有初始数组的情况下制作这个程序?

#include<stdio.h>
#include<conio.h>
void input(int);
int temp[10];
int d;
void main()
{
    int x=0;
    float avg=0,t=0;
    printf("\nHow many days : ");
    scanf("%d",&d);
    input(d);
    conv();
    for(x=0;x<d;x++)
    {
        t=t+temp[x];
    }
    avg=t/d;
    printf("Avarage is %f",avg);
    getch();
}
void input(int d)
{
    int x=0;
    for(x=0;x<d;x++)
    {
        printf("Input temperature in Celsius for #%d day",x+1);
        scanf("%d",&temp[x]);
    }
}
void conv()
{
    int x=0;
    for(x=0;x<d;x++)
    {
        temp[x]=1.8*temp[x]+32;
    }
}
Run Code Online (Sandbox Code Playgroud)

Hog*_*gan 26

在C数组和指针中密切相关.实际上,通过设计,数组只是访问指向已分配内存的指针的语法约定.

所以在C语句中

 anyarray[n] 
Run Code Online (Sandbox Code Playgroud)

是相同的

 *(anyarray+n)
Run Code Online (Sandbox Code Playgroud)

使用指针算法.

您不必担心细节使其"工作",因为它设计得有点直观.

只需创建一个指针,然后分配内存,然后像数组一样访问它.

这是一些例子 -

int *temp = null; // this will be our array


// allocate space for 10 items
temp = malloc(sizeof(int)*10);


// reference the first element of temp
temp[0] = 70;


// free the memory when done
free(temp);
Run Code Online (Sandbox Code Playgroud)

请记住 - 如果您在分配区域之外访问,则会产生未知效果.

  • @waqaslam - 静态数组不是动态的(根据定义)。是的,您确实需要释放内存。如果你不这样做,你就会有一个“内存泄漏”,这是一个常见的错误。 (2认同)

bti*_*ell 5

没有初始大小的数组基本上只是一个指针.为了动态设置数组的大小,您需要使用malloc()calloc()函数.这些将分配指定数量的内存字节.

在上面的代码中,声明temp为int 指针

int *temp;
Run Code Online (Sandbox Code Playgroud)

然后使用malloc()或为它分配空间calloc().这些函数所采用的参数是要分配的内存字节数.在这种情况下,您需要足够的空间来进行d整数.所以...

temp = malloc(d * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

malloc返回指向刚分配的内存块中第一个字节的指针.常规数组只是指向分区的内存块中第一个字节的指针,这正是temp现在的情况.因此,您可以将temp指针视为一个数组!像这样:

temp[1] = 10;
int foo = temp[1];
printf("%d", foo);
Run Code Online (Sandbox Code Playgroud)

输出

10
Run Code Online (Sandbox Code Playgroud)