Я включил несколько фрагментов кода, чтобы показать, как вы определяете начальный адрес и размер данных, хранящихся в куче и стеке. Я рекомендую вам ознакомиться с ссылками ниже, чтобы лучше понять примеры. Дайте мне знать, если у вас есть другие вопросы.
Различия между стеком и кучей
Структура памяти C Программы
Понимание памяти вашей программы
Стек
int main() {
// The following variables are stored on the stack
int i = 4;
char c = 'a';
char s[6] = "Hello";
// Starting addresses (use & operator)
printf("Starting address of i = %p\n", &i);
printf("Starting address of c = %p\n", &c);
printf("Starting address of s = %p\n", s);
// Sizes
printf("Size of i = %ld\n", sizeof(int));
printf("Size of c = %ld\n", sizeof(char));
printf("Size of s = %ld\n", sizeof(char) * 6); // 5 characters and a null character
}
Куча
int main() {
/* The following variables are pointers (i.e., they store addresses).
* The addresses they hold are locations in the heap.
* The size of the location pointed to by the pointer is
determined by the data type (int, char, etc.) */
int *i = malloc(sizeof(int));
char *c = malloc(sizeof(char));
char *s = malloc(sizeof(char) * 6);
// Place value(s) in the create memory locations
*i = 4;
*c = 'c';
strcpy(s, "Hello");
// Starting addresses (each variable i,c,s is an address)
printf("Starting address of i = %p\n", i);
printf("Starting address of c = %p\n", c);
printf("Starting address of s = %p\n", s);
// Sizes
printf("Size of i = %ld\n", sizeof(int));
printf("Size of c = %ld\n", sizeof(char));
printf("Size of s = %ld\n", sizeof(char) * 6); // 5 characters and a null character
}