Answer the question
In order to leave comments, you need to log in
What is the difference between a dynamic variable and a block variable?
A little strange question, but for some reason it haunts me. I can’t answer it, since I just started to learn C, but I can’t find a specific answer to what the difference is, well, except for the ways of writing (this is the only thing I see the difference so far :d).
A variable in a block "lives" only while that block is being executed. A dynamic variable is a piece of memory, a "label". It seems to be :d
Option one:
#include <stdio.h>
#include <malloc.h>
#include <locale.h>
int main(void)
{
setlocale(LC_ALL, "RUS");
int a, b;
printf("Введите значения для переменных \"a\" и \"b\": ");
scanf("%d%d", &a, &b);
printf("a = %d, b = %d\n", a, b);
int *c = (int*)malloc(sizeof(int));
*c = a;
a = b;
b = *c;
free(c);
printf("a = %d, b = %d", a, b);
return 0;
}
#include <stdio.h>
#include <locale.h>
int main(void)
{
setlocale(LC_ALL, "RUS");
int a, b;
printf("Введите значения для переменных \"a\" и \"b\": ");
scanf("%d%d", &a, &b);
printf("a = %d, b = %d\n", a, b);
{
int c;
c = a;
a = b;
b = c;
}
printf("a = %d, b = %d", a, b);
return 0;
}
Answer the question
In order to leave comments, you need to log in
In the first case, c is a pointer to a 4-byte allocated memory area on the heap. The variable is located in random access memory (RAM) and to access it, the processor is forced to read and write to the [relatively] slow RAM.
In the second case, c is a local variable, the compiler will most likely turn all operations on working with it into arithmetic operations with processor registers, accessing which is orders of magnitude faster than working with RAM.
example assembler pseudocode in the first case (mixed several architectures :) don't take it literally)
mov r3, #4 //размер выделяемой области 4 байта
call malloc() //выделим память
mov r28, r3 //сохраним возвращенное значение адреса памяти
str r29, r28[0] //сохраним a (r29) в выделенную память (r28[0])
mov r29, r30 //присвоим a (r29) значение b (r30)
ldr r30, r28[0] //присвоим b значение *c
mov r3, r28 //адрес для очистки памяти
call free() //удаление выделенной области
mov r28, r29 //c = a
mov r29, r30 //a = b
mov r30, r28 //b = c
Dynamic variables are needed when it is important that the variable stay in place. That is, something points to it:
struct Child {
int data;
};
struct Parent {
struct Child* child;
};
struct Child createChild(struct Parent* parent) {
struct Child result;
parent->child = &result;
return result; // parent->child будет указывать на мусор :(
}
There is a memory where all functions work, overwriting each other's values. And there is dynamic memory, which is marked as busy or freed only through special actions.
Dynamic memory, which is used through malloc()/calloc()/realloc() and free(), is needed in two cases:
1) When you don't know how much memory you will need at some point. For example, you don't know exactly what size the array will be, either 100 elements or 1000.
2) When you need to save something in one function and use it in another function. The first function, when completed, does not touch what is located in dynamic memory.
In all other cases, stack memory is used - the common memory for all functions, which they equally use for themselves, overwriting what was there before them.
If you created a block in a function, then it acts in the same place as the rest of the insides of the function (its local variables, its function calls), it's just that something like an independent piece is created there, which has a lifetime, scope, and so on. So you can even make variables a and b in it, which will be separate variables with their own values for the lifetime of the block.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question