0

I'm trying to create an array of ints, of a specified size "size." Each member of the array should be filled with 32 0s (since that's the maximum an unsigned int can take). How should I go about this? Right now I have:

unsigned int *new_array = (unsigned int*) malloc (sizeof(unsigned int) * size);
for (j = 0; j < size; j++) {
    new_array[j] = 0;
}

Yet when I print new_array[0], I get 0, not 00000000000000000000000000000000. Would bitwise operations help here?

Rtrain
  • 45
  • 6
  • try `printf("%032u", new_array[0]);` – M.M Mar 16 '20 at 03:14
  • 1
    An `int` can only hold an `int`. You might be able to encode 32 bits into an int (if ints on your target are 32 bits), but if you then print that as an int, you'll get an int, not the 32 bits. – Chris Dodd Mar 16 '20 at 03:14
  • 1
    It would be simpler (and more efficient) to use `calloc` instead of malloc with a loop – M.M Mar 16 '20 at 03:19
  • Hmm...haven't learned that but I guess now's the time. Thanks @M.M. – Rtrain Mar 16 '20 at 03:22
  • See https://www.geeksforgeeks.org/binary-representation-of-a-given-number/ for a short function that prints the binary sequence – neutrino_logic Mar 16 '20 at 03:22
  • Re "*since that's the maximum an unsigned int can take*", That's not true. An `unsigned int` might be less than 32 bits, less than 32 bits, or more than 32 bits. It depends on the system and compiler. Use `uint32_t` to get an unsigned integer exactly 32 bits in size. – ikegami Mar 16 '20 at 04:32
  • It seems that the title and description are rather misleading. The problem is not related to filling the array but only to printing integers. Printing in binary format is not mentioned in the question but for some reasons integers are expected to be a sequence of 32 `0` digits. Additionally the code for printing is not shown. Very confusing... – Gerhardh Mar 16 '20 at 10:32

1 Answers1

0
  1. Printing in binary isn't well supported in C, you'll need to roll your own at some level. Might just be easier to print hex.
  2. Leading zeroes aren't output by printf by default. Use %08x to print an 8-digit hex number (32 bits) with leading zeroes.
  3. You can call calloc to get a zero-initialized array, which would let you skip your for loop.
  4. Don't cast the return value of malloc.
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • So, even if the program doesn't show it, every element of the int is indeed filled with zeroes? So, is my code right even if it isn't printing right? – Rtrain Mar 16 '20 at 03:18
  • 2
    1. Yes, it's filled with zeros. 2. It is printing right. You asked for a decimal representation of an `int` and that's what it gave you. – Carl Norum Mar 16 '20 at 03:19