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!

5
  • 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));. Commented Jun 5, 2014 at 2: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 Commented Jun 5, 2014 at 2: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<i; array[j++] = 1); or something similar. Commented Jun 5, 2014 at 2: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! Commented Jun 5, 2014 at 3: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. Commented Jun 5, 2014 at 3:12

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

For the sake of completeness, to initialize to 0, int array[i] = { 0 }; is unbeatable for conciseness.
@Pascal, the OP array is dynamically sized. "error: variable-sized object may not be initialized"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.