Click here to Skip to main content
15,867,979 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
\\ #include<stdio.h>
#include<conio.h>
int main()
{
int num=10;
int *ptr;
*ptr=#
printf("%d",*ptr);
}
\\

What I have tried:

if i declare *ptr=&num it is showing an error (INT FROM INT MAKES INTEGER FROM POINTER WITHOUT A CAST)

if i declare int *ptr = &num its printing fine.

my question:
1) why *ptr=&num is showing an error , as i already declared the data types.
2) why if i declare int *ptr=&num is printing, should we declare int to every pointer, as it is already declared in main?
Posted
Updated 27-Jun-22 20:18pm

*ptr is dereferencing. Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.

you probably intended do this:

C++
ptr=&number;
 
Share this answer
 
v2
Pointers are a little complicated.
When you write
C
int num = 10;
you are declaring a variable that holds an integer, and assigning it a value: 10

You can do maths with that, and print it if you want:
C
int num = 10;
num = num + 100;
printf("num = %u\n", num);

When you write
C
int* ptr = #
you are declaring a variable that holds a pointer to an integer, and assigning it a value: the address of a variable.
You can then use that pointer to change the value of the variable it points to by using the * prefix to dereference the pointer:
C
int num = 10;
int *ptr = &num;
*ptr = *ptr + 100;
printf("num = %u\n", num);

This has the same effect as the original code, but you are "getting at the value" via a different route.

But ptr is not the same as num: if you change ptr it doesn't affect the value at all:
C
int num = 10;
int *ptr = &num;
ptr = ptr + 100;
printf("num = %u\n", num);
Will still print "10" because you changed the variable that points to memory, not the memory itself.

That's important, because later when you meet arrays, you will find pointers pretty handy:
C
int num[10];
for (int i = 0; i < 10; i++)
   {
   num [i] = i;
   }
int *ptr = &num;
while (*ptr < 5)
   {
   *ptr = *ptr + 100;
   ptr = ptr + 1;
   }
for (int j = 0; j < 10; j++)
   {
   printf("%u ", num[j]);
   }

And when you dereference a pointer, what you get is not a pointer - it's the type of variable the pointer points to.
So saying this:
C
int num = 10;
int *ptr;
ptr = &num;
Will give you an error because *ptr is an integer and you are trying to store an address in it.
C
int num = 10;
int *ptr = &num;
Doesn't give an error because the int * part is the declaration of the type of ptr rather than a dereference.

Make sense?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900