Subtracting two pointer in C - Structure

Hello,

I expect x to be 16 but it is 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<stdio.h>
#include<stdlib.h>

struct my
{
    char fChar;
    char sChar;
    int fInt;
    int sInt;
    int tInt;
};
int main()
{
    struct my myStruct[2];
    for(int i = 0 ; i <2 ; i++)
    {
        scanf("%d",&myStruct[i].fInt);
        scanf("%d",&myStruct[i].sInt);
        scanf("%d",&myStruct[i].tInt);
                getchar();
        scanf("%c",&myStruct[i].fChar);
        getchar();
        scanf("%c",&myStruct[i].sChar);
          
    }
    
       for(int i = 0 ; i <2 ; i++)
    {
       printf("\n%c\t",myStruct[i].fChar);
          printf("%c\t",myStruct[i].sChar);
            printf("%d\t",myStruct[i].fInt);
                printf("%d\t",myStruct[i].sInt);
                  printf("%d\t",myStruct[i].tInt);
    }
    
    int x = &myStruct[1] - &myStruct[0];
        printf("\n%d\t",x); // I expect x be 16 ( 1+1+4+4+4) but it is 1
    
    
	return 0;
}

}
Pointer subtraction is scaled by the size of the types.

For example, you have a pointer, an array and an index, these identities always hold.
p = &a[n];
noting that a[n] can be written as *(a+n).

then it follows that
n = p - a;


If you want the number of bytes, then you need to cast each pointer to a char*.
 
int x = ((char*)&myStruct[1]) - ((char*)&myStruct[0]);
int x = sizeof(myStruct[0]);
x = 16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
    my myStruct[]{{'a', 'a', 1,1}, {'b', 'b', 2,2}};


    for(int i = 0 ; i <2 ; i++)
    {
        printf("\n%c\t",myStruct[i].fChar);
        printf("%c\t",myStruct[i].sChar);
        printf("%d\t",myStruct[i].fInt);
        printf("%d\t",myStruct[i].sInt);
        printf("%d\t",myStruct[i].tInt);
    }

    long x = (long)&myStruct[0];
    long y = (long)&myStruct[1];

    printf("\n %lu\n", y - x);
    return 0;
}
Topic archived. No new replies allowed.