1 votes 1 votes Please can somebody explain how the answer is 3 not 6?? Programming in C bad-question + – atul_21 asked Sep 10, 2017 atul_21 675 views answer comment Share Follow See all 3 Comments See all 3 3 Comments reply Rishabh Gupta 2 commented Sep 10, 2017 reply Follow Share Since p1 and p2 are integers pointers. If it was char pointers answer would have been 6. 0 votes 0 votes srestha commented Sep 10, 2017 reply Follow Share Assigning character pointer inside an integer pointer will not give an error? 0 votes 0 votes saxena0612 commented Sep 10, 2017 reply Follow Share @srestha : Formal argument is itself integer ! look at the function. 0 votes 0 votes Please log in or register to add a comment.
Best answer 2 votes 2 votes You should not use an integer pointer to point to a character or anything other than int) or else the behaviour is undefined in C. Arjun answered Sep 10, 2017 • selected Sep 10, 2017 by srestha Arjun comment Share Follow See all 5 Comments See all 5 5 Comments reply Show 2 previous comments Arjun commented Sep 11, 2017 reply Follow Share yes, the code is wrong on many aspects. Just using an int pointer to point to a char itself is not valid in C -- because it can break the alignment usage and give unexpected results. Then, assuming this works; the code is using integer pointer to point to character array "GATECS" and incrementing the pointer with int size as 2. So, first comparison will be "TE" == 0, then "CS" == 0 and then "\0..." == 0, here the last "..." is junk -- it may or may not be 0 and is unallocated memory. This is another reason for the undefined behaviour. 1 votes 1 votes srestha commented Sep 11, 2017 reply Follow Share alignment usage means data alignment and data structure padding , Here problem when we do padding by.pointer conversion from char to int ? why is it comparing with o and lastly 0 is comparing with junk bits? 0 votes 0 votes Arjun commented Sep 11, 2017 reply Follow Share A data object 'X' is aligned means X always start in memory from some multiple of the alignment. For structure, this can happen and that involves structure padding. This can also happen for integers where an integer always starts from say a multiple of 4. while (*++p1); Here, ++p1 happens first. It does p1 = p1+1, which numerically becomes p1 = p1 + sizeof(*p1) as p1 is a pointer. The next part is what is missed in the question - *. '*' returns the value and p1 being an int pointer '*' returns 4 bytes (or 2 as given in the question). But only one byte for '\0' is allocated (this is done implicitly by the compiler for any string literal). 0 votes 0 votes Please log in or register to add a comment.