Answer the question
In order to leave comments, you need to log in
How much memory does an int take in C?
Confused.
Win7x64, console, MinGW.
1. Why addressing by 4 bytes?
After all, it looks like a 32-bit system, although x64 is installed.
2. Why does an int take up 4 cells (i.e. 16 bytes) and not 1 cell (i.e. 4 bytes)?
If this is true, and the minimum memory cell is 4 bytes, then it is clear why char has to take 4 bytes, and not 1 byte.
#include <stdio.h>
int main(){
int A[2] = {0};
double B[2] = {0};
char C[2] = {'A', 'B'};
for (int i = 0; i < RANGE; ++i) {
printf("%d %p\n", i, &A[i] );
}
for (int i = 0; i < RANGE; ++i) {
printf("%d %p\n", i, &B[i] );
}
for (int i = 0; i < 4; ++i) {
printf("%d %p\n", i, &C[i] );
}
printf("long%d ", sizeof(long) );
printf("int%d ", sizeof(int) );
printf("char%d \n", sizeof(char) );
return 0;
}
Массив с int
0 0028FF2C
1 0028FF30
Массив с double
0 0028FF18
1 0028FF20
Массив с char
0 0028FF16
1 0028FF17
long4 int4 char1
Answer the question
In order to leave comments, you need to log in
1. To find out addressing, type sizeof(void*) or any other pointer. It may turn out that the program was indeed compiled in x86
2. You are all right, 4 bytes per int, 1 byte per char. Each "cell" is 1 byte, not 4
The specific size of an int depends on the architecture under which it is being compiled. Since the C99 standard, platform-independent types have been added, for int they are defined in stdint.h
You need to take a 64-bit compiler and compile with the -m64
.
For example:gcc -m64 -o exmaple64 example.c
There are usually several factors involved.
- architecture. x32, x64, other processors - they can have int of different size
- alignment in memory. You can set a pragma that will force everything to align to some boundary. This is rarely used, but I remember somehow I needed the areas to be guaranteed to be aligned to 4 bytes.
For the most common case - int - 4 bytes, short int - 2 bytes, char - 1 byte
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question