简体   繁体   English

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

[英]Declaring arrays in c language without initial size

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.在 C 中数组和指针是密切相关的。 In fact, by design an array is just a syntax convention for accessing a pointer to an allocated memory.事实上,按照设计,数组只是用于访问指向已分配内存的指针的语法约定。 *( see note for more details below) *(有关更多详细信息,请参阅下面的注释)

So in C the statement所以在 C 中的语句

 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.请记住——如果您在分配的区域之外访问,您将产生未知的影响。

  • 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 中则无法执行此操作。

An array without an initial size is basically just a pointer .没有初始大小的数组基本上只是一个指针 In order to dynamically set the size of the array, you need to use the malloc() or calloc() functions.为了动态设置数组的大小,需要使用malloc()calloc()函数。 These will allocate a specified amount of bytes of memory.这些将分配指定数量的内存字节。

In your code above, declare temp as an int pointer在上面的代码中,将temp声明为 int指针

int *temp;

Then allocate space for it using malloc() or calloc() .然后使用malloc()calloc()为其分配空间。 The argument that these functions take is is the number of bytes of memory to allocate.这些函数采用的参数是要分配的内存字节数。 In this case, you want enough space for d ints.在这种情况下,您需要为d int 提供足够的空间。 So...所以...

temp = malloc(d * sizeof(int));

malloc returns a pointer to the first byte in the block of memory that was just allocated. malloc返回一个指向刚刚分配的内存块中第一个字节的指针。 Regular arrays are simply pointers to the first byte in a sectioned off block of memory, which is exactly what temp is now.常规数组只是指向分区内存块中第一个字节的指针,这正是现在的temp Thus, you can treat the temp pointer as an array!因此,您可以将temp指针视为数组! Like so:像这样:

temp[1] = 10;
int foo = temp[1];
printf("%d", foo);

Outputs输出

10

You will need to declare temp as an int pointer (instead of an int array).您需要将temp声明为int指针(而不是int数组)。 Then, you can use malloc in your main (after your first scanf ):然后,您可以在main使用malloc (在您的第一次scanf ):

temp = malloc(d * sizeof(int));

If your compiler supports c99 , then simply use VLA (variable length array).Use like this:如果您的编译器支持c99 ,那么只需使用VLA (可变长度数组)。使用如下:

void input(int);

 int d;
 void main()
 {
    int x=0;
    float avg=0,t=0;
    printf("\nHow many days : ");
    scanf("%d",&d);
    int temp[d];
    input(d);
    conv();
    for(x=0;x<d;x++)
    {
       t=t+temp[x];
    }
    avg=t/d;
    printf("Avarage is %f",avg);
    getch();
  }

Now temp[] is defined inside main() after date input.现在temp[]在输入日期后在main()定义。

1-add #include<stdlib.h> at the top of your file. 1-在文件顶部添加#include<stdlib.h> Then modify the conv() code as follows:然后修改conv()代码如下:
2- modify temp declaration as follows (global variable): 2- 修改临时声明如下(全局变量):

int *temp;

3- modify input(int d) function as follows (tested on Visual Studio 2010): 3- 修改input(int d)函数如下(在 Visual Studio 2010 上测试):

  void input(int d)
    {
        int x=0;
        temp=(int*)malloc(sizeof(int)*d);
        for(x=0;x<d;x++)
        {
            printf("Input temperature in Celsius for #%d day",x+1);
            scanf("%d",&temp[x]);
        }
    }

读取大小后,在堆上动态分配“数组”。

I didn't change anything else so you may see it clearly.我没有更改任何其他内容,因此您可以清楚地看到它。

#include<stdio.h>
#include<conio.h>
#include <stdlib.h>   //here
void input(int);
int *temp=0;  //here
int d;
void main()
{
    int x=0;
    float avg=0,t=0;
    printf("\nHow many days : ");
    scanf("%d",&d);
    temp=malloc(d * sizeof(int));  //here
    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;
    }
}

Maybe it's late to answer but... If you work with small embedded system you might not have malloc and free functions.也许回答晚了但是...如果您使用小型嵌入式系统,您可能没有 malloc 和 free 功能。 So you have to sacrifice memory for 366 * sizeof(your_type) , define it statically and use as a circular buffer.所以你必须为366 * sizeof(your_type)牺牲内存,静态定义它并用作循环缓冲区。 Then you can always slice it by number of days you need to calculate an average value.然后,您始终可以按计算平均值所需的天数对其进行切片。 Of course this makes natural constrains.当然,这会产生自然约束。 You can define it by yourself.你可以自己定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM