Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Defining Pointer Types C++

I was writing a small program to work with pointers and came across strange compiler behavior.

First case:

#include <iostream>
#include <typeinfo>


int main(int argc, char** argv)
{
    int* a,b;
    
    std::cout << typeid(&a).name() << std::endl;
    std::cout << typeid(&b).name() << std::endl;

    return 0;
}

In the first case, the program output will be like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PPi
Pi

Which, as far as I understand, means that a pointer to "a" will be of type "int**", while a pointer to "b" will be of type "int*"
This seems strange to me and I can’t understand why it works this way.

Second case:

#include <iostream>
#include <typeinfo>


int main(int argc, char** argv)
{
    int* a;
    int* b;

    std::cout << typeid(&a).name() << std::endl;
    std::cout << typeid(&b).name() << std::endl;

    return 0;
}

Second output:

PPi
PPi

And in this case, pointers receive the types that, in theory, should have received in the first case.
I have no idea where to look for information about this. There was nothing about this in the book I learned C++ from.

>Solution :

The declaration syntax comprises of a declaration specifier followed by a declarator list.

In your case, you have the simple type specifier int and a list of two declarators: *a and b.

The * prefix turns the first declarator into a pointer declarator.

The type of a is int*, and the type of b is int.

If you want both to be pointers, you would write:

int *a, *b;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading