Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Pointers in C?

Tags:

c

pointers

I have three difference examples mention below. I don't understand why ex1 has same output for ex2 and differ output for ex3, also why ex2 is not the same as ex3 where I just make a creation in another line!!

ex1

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int x=2;
    int *y;
    y = &x;
    printf("value: %d\n", *y);
    printf("address: %d\n", y);
    return EXIT_SUCCESS;
}

output

value: 2
address: 2686744

ex2

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int x=2;
    int *y = &x;
    printf("value: %d\n", *y);
    printf("address: %d\n", y);
    return EXIT_SUCCESS;
}

output

value: 2
address: 2686744

ex3

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int x=2;
    int *y;
    *y = &x;
    printf("value: %d\n", *y);
    printf("address: %d\n", y);
    return EXIT_SUCCESS;
}

output

value: 2686744
address: 2130567168

I HAVE BIG MISUNDERSTANDING OF POINTERS WHEN I THINK STAR MUST BECOME WITH (y) NOT (int) AND I FIGURE OUT THAT STAR WITH (int) NOT (y) (^_^) NOW EVERYTHING IS CLEAR FOR ME... THANKS FOR ALL YOUR ANSWERS

like image 455
thalsharif Avatar asked Dec 17 '22 02:12

thalsharif


1 Answers

In example 3, you first declare a pointer:

int *y;

and then you say that the int value of *y is the address of x.

That's because with the declaration int *y you have:

  • y is of type int *
  • *y is of type int.

So, the right lines of code in example 3 should be:

int *y;
y = &x;
like image 97
Nicolás Ozimica Avatar answered Jan 02 '23 21:01

Nicolás Ozimica