1

I want to clear some concepts

1- A pointer can only store an address , pointer itself can not store data like any other variable can. right? (as the below code doesn't run)

int *myptr;
*myptr=20;

cout<<(*myptr);

2- if you create a pointer of a class say FOO

class foo
{
public:
  int numb1 ; 
  char alphabet; 
}

// this doesn't run
void main()
{
   foo *myptr ; 
   cout<< myptr->numb1;     
}

so my question is that would the pointer of class foo (*myptr) have variables numb1 and alphabet ? if not then what's the difference between a foo pointer and a int pointer (apart from that each pointer can only point to it's respective data type)

RazaUsman_k
  • 694
  • 6
  • 20

1 Answers1

1

A pointer has enough storage to contain a number which represents a place in memory. It is perfectly possible to use this space to store other information (the information still needs to fit into the pointer's storage).

For example you could store a long value inside the pointer:

#include <iostream>
using namespace std;

int main() {
    void *ptr;
    ptr = (void*)20;

    long information = reinterpret_cast<long>(ptr);
    std::cout<<information<<std::endl;
    return 0;
}

You can try it out here and see it will output the number 20.


Edit: here with a non-void type pointer

#include <iostream>
using namespace std;

struct test{int a;};

int main() {
    // your code goes here
    test* ptr;
    ptr = (test*)20;

    long information = reinterpret_cast<long>(ptr);
    std::cout<<information<<std::endl;
    return 0;
}
Beginner
  • 5,277
  • 6
  • 34
  • 71
  • That is valid only for a **void pointer** ( that too when you explicitly convert it ) , pointers of specific data types can't store anything except addresses . right? – RazaUsman_k Apr 05 '17 at 07:56
  • No, you can to this to any pointer, i just used a void pointer, but you can modify the example to any type of pointer. – Beginner Apr 05 '17 at 07:57
  • but you would still have to explicitly convert the data so it can be stored in the pointer for example **ptr = (int * ) 20 ;** – RazaUsman_k Apr 05 '17 at 07:59
  • @RazaUsman_k yes, because withouth that the compiler assumes that you are storing a pointer in the pointer :) – Beginner Apr 05 '17 at 08:00
  • @RazaUsman_k its not a conversion, its just changing the interpretation. – Beginner Apr 05 '17 at 08:01