1
int x = 750;
int i = 0;

while (pow(2, i) < x) {
    i++;
}
printf("i is currently %d\n", i);

int array[i];

while (i > 0){
    i--;
    printf("The value of array %d is %d\n", i, array[i]);
}

When I do this, it creates some really crazy values. I've heard of trying to use malloc or memset, but the values didn't change. All I want to do is set all of these to zero so that I can use it as a counter. Thanks!

alk
  • 69,737
  • 10
  • 105
  • 255
Farion
  • 21
  • 1
  • 3
  • 5
    What, *exactly*, did this `memset` you tried *look like* when the values "didn't change" ? Post *that* please. My crystal ball tells me you invoked `memset(array, 0, i)`, where you should have invoked `memset(array, 0, i*sizeof(*array));`. – WhozCraig Jun 05 '14 at 02:47
  • Hey, thanks Craig, that is true and I didn't even realize it. I will need to rework that. Okay, also, I tried the `memset(array, 1, i*sizeof(*array));` and it shows all the values as 16843009 – Farion Jun 05 '14 at 02:57
  • 1
    Do you want them one or zero? Remember, `memset` sets *octets*; not *entities*. Setting each *byte* to 1 in a sequence of 4-byte integers gives 0x01010101 *for each `int`*, which translated to decimal is 16843009. If you want them all to be initially `1` you need to do it via a hard-loop. `for (int j=0; j – WhozCraig Jun 05 '14 at 02:59
  • That for loop at the end is exactly what I needed. I didn't realize that I could stick that `array[j++]` into the counter. Thank you so much, this is tremendously helpful! – Farion Jun 05 '14 at 03:05
  • As long as you're fixing that, you may as well fix the expensive way you're calculating i. Try `while ((1 << i++) < x);`. The version you have would allow `i` to escape the loop as zero if x were `1`. That would be *bad*, as it would result in a useless VLA. I would also encourage `unsigned int` for all of this. – WhozCraig Jun 05 '14 at 03:12

1 Answers1

3

You did not initialize your array values. Its content is garbage : the values of array[i] in your printf is not defined - it may be anything.

To initialize your array to 0, you can use memset (as commented by @WhozCraig, memset is setting all bytes of the array to the given value) :

memset (array, 0, sizeof(array));

To write something else, write a for-loop :

 int n = 0;
 for(; n < i ; ++n)
    array[n] = n; 
quantdev
  • 23,517
  • 5
  • 55
  • 88