A
A
Alexander2018-04-01 13:46:02
C++ / C#
Alexander, 2018-04-01 13:46:02

How to allocate as much dynamic memory for a variable as needed?

char t[80];
cout << sizeof t << endl; // 80 байт, всё правильно
char *p = new char[80];
cout << sizeof *p << endl; // 1 байт. Почему?

When working with static memory, exactly 80 bytes are allocated, which is true, and when working with dynamic (heap) 1 byte is allocated. Why? What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Ivanovich, 2018-04-01
@zkelo

In the first case, you get the length of a static array, sizeof works like sizeof(char)*StaticLength.
In the second case, you get the size of the first element pointed to by p. *p --> p[0] where sizeof(p[0] --> char) while *(p+1) --> p[1]
%)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question