1

I am trying to use a for loop to assign values to an array in C (I'm using minGW). At first I tried doing:

double flag[5] = {0.1};

but that only assigned the first variable in the array to 0.1. Then I tried doing a for loop to assign each individually. The reason why I don't want to hard code it is because I want the size of the flag variable to be flexible to the user's input. My current code looks like this:

    int cnt;
    double flag[5];
    for (cnt = 0; cnt < sizeof(flag); cnt++) {
        printf("sizeof(flag) is %d\n",sizeof(flag));
        printf("size is equal to %d and cnt is %d\n",size,cnt);
        flag[cnt] = 0.1;
    }
    printf("size is equal to %d\n",size);

The variable "size" changes from 6 as it was previously determined to a garbage number, and I cannot modify the number of iterations. For example, if I set cnt < sizeof(flag)-1, there is no change. -2,-5, etc no change. However if I drastically reduce the size, it gets stuck in an infinite loop. sizeof(flag) is 40, not 5 like I'd want it to be, but dividing by 8 also gets it into an infinite loop somehow. Any advice?

This question was answered, thank you everyone!

aeroware
  • 23
  • 5

4 Answers4

4

The number of elements of flag array is not:

sizeof (flag)

but

sizeof flag / sizeof *flag

The former is the size in bytes of the array, the latter is the size in bytes of the array divided by the size in bytes of one element of the array.

ouah
  • 142,963
  • 15
  • 272
  • 331
3

change :

for (cnt = 0; cnt < sizeof(flag); cnt++) 

to

for (cnt = 0; cnt < sizeof(flag)/sizeof(double); cnt++) 
chouaib
  • 2,763
  • 5
  • 20
  • 35
1

use

    for (cnt = 0; cnt < sizeof flag / sizeof *flag; cnt++)
{

}
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
1

sizeof() returns # of bytes required for that variable which is 5*sizeof(double). So your loop is running for more than 5 times causing overflow.

Apart from the solutions suggested in earlier answers, you can have a macro for size of the array and use this macro and run loop till that value.

 #define SIZE 5
 .
 .
 .
 int cnt;
 double flag[SIZE];
 for (cnt = 0; cnt < SIZE; cnt++) {
      printf("sizeof(flag) is %d\n",sizeof(flag));
      printf("size is equal to %d and cnt is %d\n",size,cnt);
      flag[cnt] = 0.1;
 }
 printf("size is equal to %d\n",size);
Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40