hi.......
i do have a doubt on this problem.please help me to solve it.here it goes........

main()
{
int x=5;
printf(“%d,%d,%d\n”,x,x<<2,>>2)
;
}
Answer: 5,20,1

now my problem is to know how the followin answer occurs?i know that its of rite shift and left shift which shifts the byte.can any one tell me clearly how tis answer comes?please....... thank you in advance.:?:

and how can we use a sizeof() in malloc operations?

Dani AI

Generated

As correctly pointed out, the shift operators work at the bit level. A few practical rules and pitfalls that were not mentioned earlier: operands undergo integer promotions before a shift, so the effective width is that of the promoted type (usually int or unsigned int). Left-shifting a value into its sign bit or shifting by a count greater than or equal to the type width is undefined behavior. Right-shifting a negative signed value is implementation-defined (some compilers do arithmetic shift, others do logical). For predictable, portable bit work, use unsigned types and ensure the shift count is between 0 and (width-1).

sizeof yields a size_t and should be used to compute bytes for allocation. A safe idiom keeps the sizeof tied to the pointer, so a later change of the pointed type does not require updating the allocation expression. Check allocation results and watch for multiplication overflow when computing total bytes.

size_t n = 5;
int *arr = malloc(n * sizeof *arr);
if (arr == NULL) {
    /* handle allocation failure */
}

Additional tips: include the proper headers (<stdlib.h> for malloc), avoid casting malloc in C (casting can hide a missing prototype), prefer new in C++, use calloc if zeroed memory is needed, and when printing sizeof values use %zu. These practices help avoid subtle bugs that are easy to miss when learning shifts and dynamic allocation.

Recommended Answers

All 2 Replies

You've pretty much answered your first question - the >> and << operators are shifting the bits of the initial value of x.

In binary, the byte that stores decimal 5 is 0000 0101. Shift that left two place, you get 0001 0100, which is 20. This new value is displayed, but the variable x is not actually modified.
So when you right shift, you again start with 5's value, and the resulting value displayed is 0000 0001. The left shift brings in zeros on the right end. The right shift dropped bits off the end.

As to sizeof when using malloc, how about

int *arr = (int * )malloc( 5 * sizeof( int ) );

malloc allocates in terms of bytes. You have to determine how many bytes will be needed for the particular data type you're using.

Val

thanks man.i got the answer 2 days before.but i want to thanks for ur attention and help.:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.