VISHMA PRATIM DAS
VISHMA PRATIM DAS

Reputation: 21

What is the difference between the two statements in c?

hope you are doing good.

Now coming to the question, How does

int *p1 = p2;

differ from

int *p1 = &p2;

any answer would be appreciated.

Upvotes: 1

Views: 106

Answers (4)

Lajos Arpad
Lajos Arpad

Reputation: 76464

Before you compare the two codes, you need to understand what a pointer is. Before you understand what a pointer is, let's speak about variables first.

Variables

A variable is a named entity which holds a value, that might change in time. The variable has a type, specified when created and the language enforces that the variable will hold that value.

Address

Now that we understand what a variable is, we need to ponder how it is stored in memory. You have your RAM memory and your variable has to have its value somewhere. However, if you randomly put the value of your variable "somewhere" in memory, without knowing where to find it, then that value, along with the variable is lost. So, when a named variable is created, its place in memory (its address) is known. You can get the address of a p2 variable by using the & operator just before it, like &p2. Therefore, the &p2 in your second example means

the address of p2

Pointers

A pointer is a variable whose type is the address of a variable of a specific kind. When you define

int *p1 = p2;

you basically create a variable, called p1 that will hold the address of an int variable. In the example above, p2 is also an int pointer, holding the address of an int variable, so you can initialize p1 to hold the value of p2 (which is a memory address of an int).

The difference

int *p1 = p2;

creates an int pointer that will be initialized to hold the value of p2 as its value, which is also an int pointer.

int *p1 = &p2;

creates an int pointer that will be initialized to hold the address of p2 as its value, which is presumably an int variable.

Upvotes: 3

enterentropy
enterentropy

Reputation: 1

-First one assigns value to the pointer

-second one assigns memory address to it and we have to use de-reference operator whenever we want to get the value.

Upvotes: 0

RAGHAV JI
RAGHAV JI

Reputation: 1

In first, lets assum that p1 have a value 10 that is assigned to p2 pointer and if p1 changes it's value not reflected to p2.

In second, lets assum p1 have a value 5 that was stored on some address assumd 6655 address that address accesed by & operator and assigned to p2 if p1 changes also reflect p2.

Upvotes: -1

Lior Pollak
Lior Pollak

Reputation: 3450

The first assignment sets p1 to whatever value is in p2.

The second assignment assigns p1 to the memory address of p2.

Upvotes: 3

Related Questions