Link to home
Start Free TrialLog in
Avatar of mcravenufo
mcravenufo

asked on

Why are these sizeof values different?

Why are these sizeof values different?

char* text = new char[10];
cout << sizeof text << endl; // produces size 4

char text2[10];
cout << sizeof text2 << endl; // produces size 10
Avatar of Axter
Axter
Flag of United States of America image

Hi mcravenufo,
because one is a size of a pointer and the other is the size of an array.

David Maisonave :-)
Cheers!
> >char* text = new char[10];
> >cout << sizeof text <

The above will just give you the size of the pointer.  It's not going to give you the size of what it's pointing to.
For example:

int *i = NULL;
char *c = NULL;
long *L = NULL;
int *i2 = new int[99];
char *c2 = new char[123];
long *L2 = new long[33];

cout << sizeof(i) << endl;
cout << sizeof(c) << endl;
cout << sizeof(L) << endl;
cout << sizeof(i2) << endl;
cout << sizeof(c2) << endl;
cout << sizeof(L2) << endl;

All of the above variables will give you the same value for sizeof, because they're all pointers.
Avatar of mcravenufo
mcravenufo

ASKER

Is there a way to find out the size of what its pointing to?

I increased the points since I am asking another question.
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you need dynamic data, I recommend that you use a vector instead or std::string
#include <vector>
using namespace std;

vector<char> text;
mcravenufo,
Why do you need to know the size?

David Maisonave :-}
>>Why do you need to know the size?

When I use strncpy I would like to know the max value that is allowed to copy.

If I just use strcpy, any amount can be copied over.
mcravenufo,
> >When I use strncpy I would like to know the max value that is allowed to copy.
If you need this information, you need to store it with the associated pointer.
If you don't save it, there's no way to find out.

I recommend you use std::string instead.  With std::string you can determined it's current size and it's total size, including unused buffer.

David Maisonave :-}
I currently use string. I am looking at some older C applications and needed to make sure I was doing things right.

Thanks!
mcravenufo,
> >I currently use string. I am looking at some older C applications and
> >needed to make sure I was doing things right.
The best you can do with C, is use a struct that contains the pointer and size allocated;

struct Data
{
  char *ptr;
  int SizeOf;
};

Data data = {new char[123], 123};

printf("data = %s\n", data.ptr);

Of course for pure C, you would replace new with malloc, and do a typedef for the struct name.
Actually, in above example I forgot to actually assign value to the data, so it's not a complete working example.
That's ok. I appreciate the help.