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

标签 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;
    }
}

最佳答案

在 C 中数组和指针是密切相关的。事实上,数组的设计只是一种语法约定,用于访问指向已分配内存的指针。 *(请参阅下面的注释以了解更多详细信息)

所以在 C 中声明

 anyarray[n] 

相同
 *(anyarray+n)

使用指针运算。

您真的不必担心使其“工作”的细节,因为它的设计有点直观。

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

这里是一些例子——

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);

请记住——如果您访问分配区域之外的区域,您将产生未知的影响。

  • To be clear it is the indexing operator ([ ]) that is translated to pointer arithmetic. This is not an array in the modern sense of the type. Whether (or not) the pointer involved points to (dynamically) allocated memory is inconsequential to how this operator works. In a more modern language you would be able to operate on the array as an abstract type (to see how big it is, for example), you can't do this in C.

关于c - 用c语言声明没有初始大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381867/

相关文章:

arrays - Swift 中数组、集合和字典的区别

c - 如何从命令行正确传递文件路径?

javascript - QtQuick Item.children.indexOf() 不存在?

c++ - 试图引用已删除的函数

c - _BIG_ENUM=0xFFFFFFFF 在枚举的最后是什么意思?

c++ - 如何使用 OpenLDAP API 选择 LDAP 客户端绑定(bind)到哪个地址?

c++ - “_snprintf”未在此范围内声明

Javascript - 接受参数并返回包含 "x"的字符串的函数

c - 如何用 C 语言创建通用的个性化函数,然后将它们包含在您的程序中?

c - 如何在C中向后读取文件?