Lee William
Lee William

Reputation: 125

How to understand the pointer when assign value in integer and single character in C?

I try to change something a little when assigning value and things suddenly get a lot more complicated and result become mysterious. I don't mean to make code dirty, I just want to compare difference to help myself better understand.

#include <stdio.h>

int main() {

    int h = 10;
    int *i = &h;
    int j = &h;
    int *k = h;
    printf("%i;%p\n", h, &h);
    printf("%p;%i;%p\n", i, *i, &i);
    printf("%i;%p;%p\n", j, j, &j);      //how to print out h by j?
    printf("%i;%p\n\n", k, &k);        // how to print out *k?

    char a = 'M';
    char *b = &a;
    char c = &a;
    char *d = a;
    printf("%c;%p\n", a, &a);
    printf("%p;%c;%p\n",b, *b, &b);
    printf("%c;%p;%p\n", c, c, &c);        //how to print out a by c?
    printf("%c;%p\n", d, &d);        //how to print out *d?

    return 0;
}

The result is:

10;0xbfcef838
0xbfcef838;10;0xbfcef83c
-1076955080;0xbfcef838;0xbfcef840    //where does -1076955080 come from?
10;0xbfcef844

M;0xbfcef836
0xbfcef836;M;0xbfcef848
6;0x36;0xbfcef837        //where does 6 come from?
M;0xbfcef84c

Upvotes: 0

Views: 72

Answers (1)

pm100
pm100

Reputation: 50110

Your code doesn't even compile (in ideone as c++, c probably warns)

int h = 10;
int j = &h;

Is not valid . You mean

int h = 10;
int *j = &h;

Which says that j is a pointer to an int (int *j) and it is initialized to point at h (= &h);

To pring h by j

printf("%d\n", *j);

Think of it this way. int *j says that *j is an int. So you have to type *j when you want the int that j points at

Upvotes: 1

Related Questions