Home > Software engineering >  Trying to make array size dynamic without use of malloc or calloc or pointers
Trying to make array size dynamic without use of malloc or calloc or pointers

Time:03-11

So I am trying to allocate memory dynamically by incrementing array size as user wants by updating the array size every time the loop runs as you can see the code below.

As you can see here, I have initialized int score[n]; in the beginning and again in the for loop because I want to update the size of the array dynamically. Although the array size do get updated dynamically and I am able to store the values while I am in that loop (I can even print out those values ) , all the stored data becomes useless ( gets destroyed) when I come out of that loop after break; and the array size of score[n] becomes 1 again , even though I have given let say 3 values

#include<stdio.h>
int main()
{
int n=1;
int score[n];
int sum=0;
float average;
for(int i=0;i<n;i  )
{
    int score[n];
    printf("enter scores\n");
    scanf("%d",&score[i]);
    int option;
    printf("press 1 to add more scores or 0 to exit\n");
    scanf(" %d",&option);
    if(option==0)
    {
        printf("The scores are:-\n");
        for(int i=0;i<n;i  )
            {
                printf("%d\n",score[i]);
                sum=sum score[i];
            }
        average=sum/3.0; // to specify the computer to treat sum also as float I used 3.0
        printf("The average is:- %f",average);

        break;
    }
    n  ;
}
}

I have also shared a screenshot of debug console. Also this is a screenshot of code that I typed before. The code which I have shown above is updated code , this was just to show how array size has been allocated dynamically but becomes useless right after it comes out of that for loop after break;

This is While I am inside the for loop , where the array values are getting updated

The is after coming out of the loop after break;

I am really new to C , Can someone please tell what exactly is happening here? if I am not allowed to redeclare the same variable again , how am I able to declare it within for loop without any error? What actually happens when we initialize the same variable again?

How is the array storing the values correctly after every iteration of for loop even after me re-initializing score[n]; array? And Why does the stored value of array gets destroyed after breaking of the loop as you can see in that second picture?

Thank you

CodePudding user response:

what is actually happening is that when you declare the int score[n] inside the for loop, it is getting allocated a new memory location, you can check with printf("%p\n", score);, with its scope limited to the for loop only, hence you are able to redeclare within that block(for loop). Hence after 'break' gets executed and we come out of loop the initial int score[n] has not changed since declaration and thus is an empty array and hence your output. Regarding the int score[n] printing and updating its code inside for loop. Now regarding how array is able to store values dynamically, we know array stores values in continuous memory so if the space is free it will keep storing the values, note that you are using score[i] in scanf() not score[n], and since 'i' keeps increasing in each iteration the values keep getting added in the block of memory when we declared int score[n] in the for loop. Since, the block is same address of score array is not changing ( again check with printf("%p\n", score); ) and thus with each increasing 'i' it is storing values in the array.

CodePudding user response:

First, the problem in your code is that score outside the for loop is different from the score inside the for loop. If you tried to "redeclare" score as you did, outside the for loop, your program would not compile. When you exit the for loop, the score you had been working on is deleted, as it was on every loop iteration.

You are tricking yourself into believing your score array isn't reset because you get lucky with the memory, but testing your code I get random values thrown in from time to time.

enter scores
45
press 1 to add more scores or 0 to exit
1
enter scores
46
press 1 to add more scores or 0 to exit
1
enter scores
47
press 1 to add more scores or 0 to exit
1
enter scores
48
press 1 to add more scores or 0 to exit
1
enter scores
50
press 1 to add more scores or 0 to exit
1
enter scores
52
press 1 to add more scores or 0 to exit
0
The scores are:-
4
0
626127794
21878
50
52

Dynamically changing the array size must be done using pointers, malloc and realloc, I strongly advise you learn how to use them.

If you want to start with something easier: why not set the size of the array to something big (say 1000) at the beginning and prevent the user from entering more than that value?

On another note, average = sum/3.0; should be average = sum/(float)n;

Happy learning

  • Related