-3

I just started working with C and came across a line of code I don't understand. Could someone explain what it does?

short int * work = (short int *) malloc(1000*16);
Brad
  • 159,648
  • 54
  • 349
  • 530

4 Answers4

5

What don't you understand exactly? The code declares a short int* which is a pointer to one or more 16 bit (at least 16 bit) signed integers. It initializes it to a pointer returned by malloc, which is a chunk of memory large enough to fit 1000 * 16 bytes.

Now, why did they use 1000 * 16? I don't know. Typically you would allocate along the lines of num_elements * sizeof(element), i.e., num_elements * sizeof(short int).

More canonically, use num_elements * sizeof(*work) so that your code doesn't break if you change the type of the pointer.

Also note that it is a bad idea to cast the return value of malloc in C.

Community
  • 1
  • 1
Ed S.
  • 122,712
  • 22
  • 185
  • 265
2

Let's break it down:

  • short int * work

This declares a pointer to an int, called work. It's declared as a short int, which means that it must be:

  • at least 16 bits in length (or two 8 bit bytes), and
  • not bigger than a plain int.

Generally, shorts are used when an int may be too large. Wikipedia has an excellent breakdown of C data types here: http://en.wikipedia.org/wiki/C_data_types

  • = (short int *) malloc(1000*16);

This allocates 1000*16 bytes, and assigns it to the pointer. You can read more about malloc() in the malloc() man page. This particular line is an example of bad style because:

  • It's unnecessary to cast the result of malloc - see Do I cast the result of malloc?
  • Because the size of a short int isn't defined in a standard, this line isn't guaranteed to produce any particular number of short ints.

It would be better to instead write:

short int * work = malloc(sizeof(short int) * NUMBER_OF_SHORT_INTS_REQUIRED);

or, even better:

short int * work = malloc(sizeof(work[0]) * NUMBER_OF_SHORT_INTS_REQUIRED);

Remember to check to make sure that malloc hasn't returned NULL before doing anything with work.

Community
  • 1
  • 1
Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
2

You are reserving (dynamically = on run-time) 1000 * 16 = 16000 bytes by using malloc. Using malloc what you get is a pointer to the address of the first byte of the 16000 bytes that have been reserved. You store the result to the pointer that you have for short integers named "work". Typically, every short integer has size 2 bytes, so, essentially malloc has reserved space for 8000 short integers (assuming it succeeded).

If malloc failed to allocate the space, it returns NULL.

Finally, it is bad practice to cast what malloc has returned.

MightyMouse
  • 13,208
  • 8
  • 33
  • 43
2

Saw "declarations" in your title.

They have a very good web site for complex declarations. here

Kaunteya
  • 3,107
  • 1
  • 35
  • 66