【C】Pointer (3) Run Program Which Uses Pointers

※ 日本語ページはこちら

Let’s write a program, compile it and run it.

Step0: Confirmation about environment.

$ gcc –version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Step1: Program

#include <stdio.h>

int main()
{
        int a;
        const int b = 10;
        int *p;

        a=1;
        p=&a;

        printf("a's value is %d \n", a);
        printf("a's address is %p \n", &a);
        printf("p's value is %p \n", p);

        a++;

        printf("a's value is %d \n", a);
        printf("a's address is %p \n", &a);
        printf("p's value is %p \n", p);

        p=&b;
        printf("b's value is %d \n", b);
        printf("b's address is %p \n", &b);
        printf("p's value is %p \n", p);

        *p = 11;
        printf("b's value is %d \n", b);
        printf("b's address is %p \n", &b);
        printf("p's value is %p \n", p);

        return 0;

}

Step2: Compile command and result of compile.

$ gcc 03_1.c
03_1.c: In function ‘main’:
03_1.c:22:3: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
p=&b;
^

As above warning shows , const is ignored when you access b through pointer, so you can overwrite the value of b through pointer.

Step3: Execution Result.

$ ./a.out
a's value is 1
a's address is 0x7ffc5ccd5ff0
p's value is 0x7ffc5ccd5ff0
a's value is 2
a's address is 0x7ffc5ccd5ff0
p's value is 0x7ffc5ccd5ff0
b's value is 10
b's address is 0x7ffc5ccd5ff4
p's value is 0x7ffc5ccd5ff4
b's value is 11
b's address is 0x7ffc5ccd5ff4
p's value is 0x7ffc5ccd5ff4

As you confirmed、pointer can store not only an address of a variable , but also an address of const  and you can change the value of const if you access it through the pointer.

That’s all for this time.