How to see how much memory occupies such a variable of type int, char e long
in C ++?
And how do you use #define
?
How to see how much memory occupies such a variable of type int, char e long
in C ++?
And how do you use #define
?
#define
should not be used in C ++ (actually not even in modern C), use a constant with the keyword const
. Anyway I showed an example of #define
.
I made an example in C ++ standards showing the size of the variables as you requested. Note that sizeof
is an operator, it does not even need parentheses in some situations. This operator takes the data size used as operand, in this case the variable, at compile time, so it has no cost at runtime.
In general in C ++ do not use legacy C libraries.
#include <iostream>
#define tamanho 10
const int elementos = 10;
using namespace std;
int main() {
int a = 1;
char b = 'a';
float c = 1.0f;
double d = 2.0d;
short e = 1000;
long f = 100000;
int *g = new int[tamanho];
int h[elementos];
cout << "a tem " << sizeof(a) << " bytes\n";
cout << "b tem " << sizeof(b) << " bytes\n";
cout << "c tem " << sizeof(c) << " bytes\n";
cout << "d tem " << sizeof(d) << " bytes\n";
cout << "e tem " << sizeof(e) << " bytes\n";
cout << "f tem " << sizeof(f) << " bytes\n";
cout << "g tem " << sizeof(g) << " bytes\n"; //provavelmente não é o resultado esperado
cout << "h tem " << sizeof(h) << " bytes\n";
return 0;
}
See running on ideone .
Note that allocating data dynamically can lead to problems determining the size of the allocation. You would have to have other ways of figuring out the allocated size. But also note that in this case the size of the variable really is the size of the pointer. The result is not wrong. The variable itself occupies 4 bytes in 32-bit architectures. What the pointer points to is that it will have another extra size, it shows in the variable h
(static allocation) that was not allocated with a pointer as it was in g
(dynamic allocation).
Learn more about the difference in stack and heap .
the define works like this:
#define TAMMAX 100
first comes the next defines the name and what it contains in that name,
when and compiled everything that is named TAMMAX
in your code and replaced with 100, for example:
int vetor[TAMMAX] // vetor de 100 indices
You can find out how many bytes a variable occupies through the sizeof()
function.
This function takes a variable as an argument, or reserved words that represent the variables: char, int, float, etc.
Example:
printf("Char: %d bytes\n", sizeof(char));
printf("Int: %d bytes\n", sizeof(int));
printf("Float: %d bytes\n", sizeof(float));
printf("Double: %d bytes\n", sizeof(double));
Do not forget to include the stdio.h
To use the define is very simple:
#define CONTADOR 0
Then just use the name of define
in the code.
Example:
#define CONTADOR 10
int main() {
int vetor[CONTADOR]; //Vetor com CONTADOR posições
}