Romi
Romi

Reputation: 13

C++ pointer to char

#include<iostream>

namespace std;

void main(){
    char *ch;
    char nch;
    cout<<"\n"<<sizeof(ch);
    cout<<\n"<<sizeof(nch);
    cout<<"\n"; 
    return 0;
} 

This program would print the output as:

8
1

Why does the size of char type change when it is a pointer?

Upvotes: 1

Views: 148

Answers (4)

Gasper
Gasper

Reputation: 3030

Pointers are not the data they're pointing to and char * is not the same type as char.

Most pointers have the same size and it's generally machine architecture dependent, in your case it happend to be 8 bytes, so you pretty much can expect something among the lines:

int* pInt;
char* pChar;
std::cout << (sizeof(pInt) == sizeof(pChar)); // prints 1 for true

On the other hand sizeof(char) is guaranteed to return 1. But this still doesn't guarantee the ammount of actual memory used to store it, funny enough.

If you want to get the size of actual data pointed to by the pointer you, of course, can dereference it:

std::cout << sizeof(*ch); // prints 8

Upvotes: 2

sjsam
sjsam

Reputation: 21965

sizeof *ch

The catch is that ch is a pointer to char, so ch is not a char. It just stores an address. For storing an address, it needs some space and in many systems, that happen to be 8 bytes

sizeof(nch)

prints the size of char type in a system and it is 1 byte.

Upvotes: 0

Teivaz
Teivaz

Reputation: 5675

Pointer to char is not a char, it is a pointer. Size of a pointer does not depend on the size of the object it points to. Because pointer is basically an address of the first byte of the object.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182847

It doesn't, but the size of a pointer may be different than the size of a character. If you change your code from sizeof(ch) to sizeof(*ch), then you'll get 1 1.

Upvotes: -1

Related Questions