17

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;
    }
}
5
  • 1
    Is your compiler supports c99?
    – haccks
    Commented Jun 29, 2013 at 15:48
  • 2
    1) #include<conio.h> non-standard header 2) void main() main() should return int. Commented Jun 29, 2013 at 15:59
  • how to check is my compiler supports c99. i'm beginner for C language :)
    – ViSTA
    Commented Jun 29, 2013 at 16:24
  • BTW: temp[x]=1.8*temp[x]+32 performs a truncate-towards-zero rounding, biasing inexact results toward 0. Recommend ‘(int) round(1.8*temp[x]+32)’. You'll get a better average in the end. (The usual idiom +0.5 only works here if all conversions are positive.) Commented Jun 29, 2013 at 18:05
  • Why the PO does not accept or apparently vote up answers? Commented Nov 3, 2014 at 18:38

8 Answers 8

28

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. *(see note for more details below)

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.

  • 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.
11
  • is it necessary to explicitly free the memory? what if my array is static?
    – waqaslam
    Commented Jun 19, 2018 at 7:00
  • 2
    @waqaslam - a static array is not dynamic (by definition). Yes you do need to free the memory. If you don't you will have a "memory leak" a common bug.
    – Hogan
    Commented Jun 19, 2018 at 13:38
  • 1
    This answer is a bit misleading, having confused at least one reader into thinking that after allocation, temp would be the identifier of an array. This is not the case. An object declared as an int * is always and only an int *, not an array. In most ways, the allocated space can be used via the pointer as if the pointer were an array, but that doesn't make it one in fact, and there are expressions by which the difference can be detected. In particular, some involving sizeof. Commented Jan 15, 2020 at 19:46
  • 1
    @Hogan, I know it's an old answer. I commented because the user who posed a current question (linked in my original comment) misunderstood this answer in just the way I described (they referred specifically to this answer). I honestly supposed that you would probably ignore the comment, which I think serves as sufficient clarification. Nevertheless, I do think that "an array is just a syntax convention for accessing a pointer to an allocated memory" indeed is potentially misleading to anyone who doesn't already know what you mean. Commented Jan 16, 2020 at 23:28
  • 1
    @scott -- temp is a pointer the size is defined by the OS -- eg a 32 bit OS is 32 bits and a 64 bit OS is 64
    – Hogan
    Commented Sep 9, 2021 at 14:37
5

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. These will allocate a specified amount of bytes of memory.

In your code above, declare temp as an int pointer

int *temp;

Then allocate space for it using malloc() or 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. So...

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

malloc returns a pointer to the first byte in the block of memory that was just allocated. Regular arrays are simply pointers to the first byte in a sectioned off block of memory, which is exactly what temp is now. Thus, you can treat the temp pointer as an array! Like so:

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

Outputs

10
2

You will need to declare temp as an int pointer (instead of an int array). Then, you can use malloc in your main (after your first scanf):

temp = malloc(d * sizeof(int));
4
  • i can't understand what you say. i was trying it like this printf("\nHow many days : "); scanf("%d",&d); int temp[d]; but it's not working :(
    – ViSTA
    Commented Jun 29, 2013 at 15:55
  • You need to change the line int temp[10] to int *temp. Then, instead of doing int temp[d], use the code I provided in my answer. Commented Jun 29, 2013 at 16:08
  • i don't about malloc. can you please tall me how can i use this for my program.
    – ViSTA
    Commented Jun 29, 2013 at 16:17
  • malloc basically lets you reserve some memory for whatever purpose you need it for, but when you don't know the size ahead of time. en.wikipedia.org/wiki/C_dynamic_memory_allocation might be a good place to start Commented Jun 29, 2013 at 17:28
2

If your compiler supports c99, then simply use VLA(variable length array).Use like this:

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.

8
  • @Down voter,it is clear from his post that he has very little knowledge of pointers......keep in mind>
    – haccks
    Commented Jun 29, 2013 at 16:00
  • @user2534857, which compiler are you using?
    – haccks
    Commented Jun 29, 2013 at 16:16
  • @user2534857; Give me information about your compiler/IDE(code::block,Dev-c++,Visual basics etc)
    – haccks
    Commented Jun 29, 2013 at 16:20
  • @Hogan; Then why did't he accepted yet any answer explained by pointer,although answers are correct?
    – haccks
    Commented Jun 29, 2013 at 16:25
  • @haccks you will have to ask him :D
    – Hogan
    Commented Jun 29, 2013 at 16:27
1

1-add #include<stdlib.h> at the top of your file. Then modify the conv() code as follows:
2- modify temp declaration as follows (global variable):

int *temp;

3- modify input(int d) function as follows (tested on 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]);
        }
    }
1
  • First, don't forget to deallocate temp at the end of main(...). Second, I would advise both allocating and deallocating temp within the main(...) function, instead of allocating in input(...) and deallocating in main(...).
    – Jeff G
    Commented Feb 15, 2016 at 23:02
0

Allocate the "array" dynamically on the heap after you read the size.

2
  • 1
    Why not just allocate the array with the needed size in the first place? Commented Jun 29, 2013 at 15:43
  • @DrewMcGowen You're right, I didn't read the code and didn't see that the size is read. Updated answer to reflect that. Commented Jun 29, 2013 at 15:45
0

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;
    }
}
1
  • it's got some error "malloc should have prototype" how to fix it.. plz
    – ViSTA
    Commented Jun 29, 2013 at 16:26
0

Maybe it's late to answer but... If you work with small embedded system you might not have malloc and free functions. So you have to sacrifice memory for 366 * sizeof(your_type), define it statically and use as a circular buffer. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.