How is the output of this program?

I have a piece of code written in C where pointer arithmetic is performed. I would like to know how the result will be like that?

#include <stdio.h> int main() { char arr[] = "gookmforgookm"; char *ptr1 = arr; char *ptr2 = ptr1 + 3; printf ("ptr2 - ptr1 = %d\n", ptr2 - ptr1); printf ("(int*)ptr2 - (int*) ptr1 = %d", (int*)ptr2 - (int*)ptr1); getchar(); return 0; } 

The result is below:

 ptr2 - ptr1 = 3 (int*)ptr2 - (int*) ptr1 = 0 
+6
source share
5 answers

Strictly speaking, you invoke undefined behavior, and any result that the program produces is in order according to the C standard.

However, you are probably on a machine where sizeof(int) == 4 (as opposed to 2). Since for an integer of 4 bytes, two addresses divided by 3 bytes are part of the same integer, so the difference between the addresses is 0 * sizeof(int) . You could find another answer if you chose ptr1 = arr + 1; otherwise you cannot. But what is the beauty of undefined behavior - that would be β€œright” anyway.

+6
source

After subtraction, you need to divide the result by the size of the pointed type.

 (int*)ptr2 - (int*)ptr1 == (0x1000003 - 0x1000000) / sizeof(int) (int*)ptr2 - (int*)ptr1 == (0x1000003 - 0x1000000) / 4 == 0 
+4
source

ptr1 and ptr2 are both char * types, which means one byte per pointer.

 char *ptr2 = ptr1 + 3; 

So

 ptr2 - ptr1 = 3 

Then you press both pointers of type int * , int enter 4 bytes, so that both pointers are aimed at the same int , both pointers have the same value through memory alignment, you will get 0 result.

+1
source

When you subtract two pointers while they point to the same array, the result will be the number of elements separating them.

Subtracting and comparing a pointer

0
source

The memory addresses of elements of the same array are always sequential. those. if the memory address is myarray [0]:

  0x4000000 

then the memory address myarray [2] will definitely be

  0x4000002 

So when you store the address arr in ptr1 , assume that it is x , and then when you make the address ptr2 , three units higher than ptr1, it will be x + 3 . So when you subtract ptr1 from ptr2, the answer is as follows:

( x +3) - x = 3

Hence the answer.

In the second expression of printf (), if you want it to display the same result as above (3), you need to convert the pointer to int , not int* .

 char *myvar; // given contents somewhere int addr = (int)myvar; // addr now = the char pointer 

So in your case:

 printf ("(int)ptr2 - (int) ptr1 = %d", (int)ptr2 - (int)ptr1); 
0
source

Source: https://habr.com/ru/post/903736/


All Articles