C Language Pointer and Array Inquiries

Asked 2 years ago, Updated 2 years ago, 87 views

Hello.

I have a question about pointer and arrangement in C language.

Why do I see the same number as 1 if I do p-myarr like the following code?

If you calculate based on the output address value, you should get 0x7ffc279f5054 - 0x7ffc279f5050 = 4, but I wonder why you get 1.

Code

#include <stdio.h>

int main(void) {
    int myarr[10] = {1,2,3}; 
    int *p = myarr;


    printf("arr memory :      %p\n", &myarr); 
    printf("pointer memory :  %p\n", p);

    for(int i =0; i<3; i++){
        p++;
    printf("pointer up address :  %p\n", p); 
        printf("pointer    :   %d\n", p-myarr); 
    }
}

Output

arr memory :      0x7ffc279f5050
pointer memory :  0x7ffc279f5050
pointer up address :  0x7ffc279f5054
pointer    :   1
pointer up address :  0x7ffc279f5058
pointer    :   2
pointer up address :  0x7ffc279f505c
pointer    :   3

pointer array

2022-09-22 19:03

1 Answers

The operation of the pointer is based on the size of the data type's memory.

If you look at the example you asked, when you p++,

0x7ffc279f505*0* -> 0x7ffc279f505*1*, not changed to

You can see that it has changed to 0x7ffc279f505*0* -> 0x7ffc279f505*4*.

The ++ operator increased by 1, but the memory address increased by 4.

This means that one int data type occupies 4 bytes of memory on the questioner's computer.

Likewise, the same principle was applied to subtraction operations, resulting in a difference of 4 bytes, but the byte is 1 because of one space in the int-type data type.


2022-09-22 19:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.