声明在C语言中数组没有初始大小 [英] Declaring arrays in c language without initial size

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

问题描述

编写一个程序来操作温度详情如下。结果
- 输入要计算的天数。 - 主要功能结果
- 输入摄氏温度 - 输入功能结果
- 从摄氏转换温度Fahrenheit.-单独的函数结果
- 找到华氏温度的平均值。

我怎样才能使这个方案没有数组的初始大小??

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;
无效输入(INT);
INT温度[10];
INT D组;
无效的主要()
{
    INT X = 0;
    浮动平均= 0,t = 0时;
    的printf(\\ NHOW多天:);
    scanf函数(%D,和D);
    输入(四);
    CONV();
    为(X = 0; X&下,D,X ++)
    {
        T = +温度[X];
    }
    平均T / D;
    的printf(Avarage是%F,AVG);
    残培();
}
无效输入(INT D)
{
    INT X = 0;
    为(X = 0; X&下,D,X ++)
    {
        的printf(输入温度在摄氏#%d日,X + 1);
        scanf函数(%d个,&安培;临时[X]);
    }
}
无效CONV()
{
    INT X = 0;
    为(X = 0; X&下,D,X ++)
    {
        温度[X] = 1.8 *温度[X] +32;
    }
}


解决方案

在C数组和指针有着密切的关系。事实上,由设计的阵列仅仅是用于访问一个指向分配的存储器语法约定。

那么在C语句

  anyarray的[N]

是相同的

  *(anyarray的+ N)

使用指针运算。

你真的不担心的细节,以使工作,因为它的设计是有些直观。

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

下面是一些例子 -

 为int * TEMP = NULL; //这将是我们阵
// 10项分配空间
TEMP =的malloc(sizeof的(INT)* 10);
//参考温度的第一元件
温度[0] = 70;
//完成后释放内存
免费(TEMP);

记住 - 如果你访问分配的区域你将有未知的影响之外。

Write a program to manipulate the temperature details as given below.
- Input the number of days to be calculated. – Main function
- Input temperature in Celsius – input function
- Convert the temperature from Celsius to Fahrenheit.- Separate function
- find the average temperature in Fahrenheit.

how can I make this program without initial size of array ??

#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;
    }
}

解决方案

In C arrays and pointers are closely related. In fact, by design an array is just a syntax convention for accessing a pointer to an allocated memory.

So in C the statement

 anyarray[n] 

is the same as

 *(anyarray+n)

Using pointer arithmetic.

You don't really have to worry about the details to make it "work" as it is designed to be somewhat intuitive.

Just create a pointer, and allocate the memory and then access it like as an array.

Here is some examples --

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

Remember -- if you access outside of the allocated area you will have unknown effects.

这篇关于声明在C语言中数组没有初始大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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