Question

Here's the snippet

main(){
//
  while(){
  int b;
  scanf("%d",&b);
  int arr[b];
  }
}

Ok now, Since I don't know the exact bound of array, I have to take in as a variable*using scanf*. And the array created contains garbage value. And for that purpose I have to initialize each element to 0, because that is what I want.

Is there a way I can get this thing to work, without having to initialize every time inside the loop?

Thanks

EDIT I guess I can use calloc to allocate the memory. Will there be a different in memory used?

Was it helpful?

Solution

If you need an array of run-time size, then the proper approach depends on how large your array is going to be.

If the value of b can be large, then declaring it as a local array can lead to stack overflow. In that case the better idea would be to dynamically allocate your array using calloc. calloc will properly zero-initialize an int array.

If the array is relatively small and safe to allocate on the stack, the you can simply declare it as a local array (which is what you did in your original code) and then set it to all-zeros by using memset(arr, 0, sizeof arr).

Of course, in both cases you might end up with a hidden memory-zeroing cycle implemented inside the library function. In general case it is not possible to set a large region of memory to zero without using a cycle.

OTHER TIPS

If your compiler supports C99 then you can easily use VLA's;

int a, b; 
printf("Enter size of array: ");
scanf("%d",&b);

int arr[b];

and to initialize its all elements to zero in your case use an inner loop or standard library function memset.

memset(b, 0, sizeof(b));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top