0

First of all, I'm sorry if this question is stupid and I'm beginner in C/C++

My question is:

Why when I want to point to a char variable like ( char x = 'A' ) I should make a pointer of char datatype? like this one ( char * pnt = &x ) ? I thought the address should be always integer of any place in Memory so the variable x in my example stored in RAM like this format (01000001) after converted (65) to the binary system in some address .. so there is an address of char type ??

I didn't understand the concept, any explanation?

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Mahmoud Sami
  • 55
  • 2
  • 9
  • 1
    Underneath, they are all just pointers to memory, and work the same. The type system is part of the C++ layer over the top, that helps you make sure you don't access, say, an `int` as a `float` by mistake. The memory itself can't tell the difference. – BoBTFish Feb 08 '17 at 07:49
  • By this way it is possible to do a type checking at compile time, and prevent you (or at least it tries to prevent you) from doing mistakes. – Pierre Feb 08 '17 at 07:49
  • _so there is an address of char type_ NO. Memory address are always intergers. Here, `char * pnt = &x` means that the variable `pnt` stores the address(which is always integer) of a memory location which contains a char type data. So, different pointer types tell the compiler about the type of the data stored at the memory location pointed by the pointer. – Avantika Saini Feb 08 '17 at 12:10

1 Answers1

0

That's because of strong typing in C/C++. That is one of the paradigms (python uses different one for example), but the only possible in C++. You actually can use your knowledge about pointer types and transform pointer between types. Use static_cast, dynamic_cast and so on to do this. Also if you are using C you can define a pointer to "something" - void*. This one can point to char, to int or to other type you can imagine. Notice: such transformation should be conscious. This can be a symphtom of a bad architecture or other troubles.

Vladimir Tsyshnatiy
  • 989
  • 1
  • 10
  • 20
  • This is because the size allocated for different data types are different. So if it is an integer 2 bytes will be allocated, for char it is 1 byte. Data type is given to pointer to tell how much bytes it should read. This is called dereferencing so that the pointer knows how much data it should read from the address it is pointing to. – Ishan Tiwary Feb 08 '17 at 07:59
  • Yep, nice point. For some reason I've assumed that and did not point to this into my answer. Thank you! – Vladimir Tsyshnatiy Feb 08 '17 at 08:01
  • Also pointer arithmetics will not work without proper size. – Gerhardh Feb 08 '17 at 08:52