0

If a data type of char is 1 byte, then should not a char pointer to it also be 1 byte? Why do I have extra data in my char pointer [8 bytes]?

#include <iostream>
#include <conio.h>

using namespace std;

int main (  );
void ShowCharacter ( char *p_character );

int main (  )
  {
  char character = '\0', *p_character;
  p_character = &character;
  int size = sizeof ( p_character );

  cout << "Pass a variable 'char character' as a pointer!" << endl;

  character = getch (  );

  ShowCharacter ( p_character );
  cout << "Character (main): " << character << " (size: " << size << ")" << endl;

  return ( 0 );
  }

void ShowCharacter ( char *p_character )
  {
  char letter = p_character [ 0 ];  
// Data type Array >> sizeof ( p_character ) is 8 bytes, why is it an array and not 
// a char? 

  int size = sizeof ( p_character );

  cout << "Character (ShowCharacter): " << letter << " (size: " << size << ")\n";
// change letter to p_character to see what I mean.

return;
}

I am trying to write my first game of tic-tac-toe in C++. Understanding this will help me.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 3
    "should not a char pointer to it also be 1 byte?" No, of course it should not. If it were, you could only ever have 256 distinct `char` objects. A `char*` pointer doesn't store that one byte - it stores the memory address of that byte. Your computer's RAM has more than 256 distinct addresses. – Igor Tandetnik Sep 19 '21 at 00:12
  • 2
    "should not a char pointer to it also be 1 byte?": Please explain your reasoning for thinking it should be so that we can identify the misunderstanding. For example, are you thinking that "char pointer" is a kind of "char"? – Scott McPeak Sep 19 '21 at 00:22
  • *"I am trying to write my first game of tic-tac-toe in C++. Understanding this will help me."* -- it will? How? You might be worrying too much about insignificant details. If I were to write a tic-tac-toe game, I doubt the exact size of data types would be relevant to any of my code. (At best, I might utilize the fact that `sizeof(char) <= sizeof(char*)`.) – JaMiT Sep 19 '21 at 00:28
  • Does this answer your question? [Is the sizeof(some pointer) always equal to four?](https://stackoverflow.com/questions/399003/is-the-sizeofsome-pointer-always-equal-to-four) or perhaps [sizeof a pointer](https://stackoverflow.com/questions/15538210/sizeof-a-pointer), for more of a "why" question. – JaMiT Sep 19 '21 at 03:53

1 Answers1

0

It's because a pointer is a type of it's own and it's for holding memory addressees. (It doesn't matter if it is the address of a char, int, etc.)

On your system, the pointer type is 8 bytes long so it can store an 8 byte (64 bit) address (but its size depends on the system).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
BenMx5
  • 1