A
A
Anton Styazhkin2016-09-17 21:02:09
C++ / C#
Anton Styazhkin, 2016-09-17 21:02:09

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;	
}

Option two:
#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;	
}

Both that, and other variable live not eternally. My question is this: "what is the difference between the variable "c" in the two variants?".

Answer the question

In order to leave comments, you need to log in

3 answer(s)
1
15432, 2016-09-17
@untonyst

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() //удаление выделенной области

it should be noted that reading and writing from RAM are relatively slow operations
in the second case, the compiled code will be much more compact and will be executed almost instantly
mov r28, r29 //c = a
mov r29, r30 //a = b
mov r30, r28 //b = c

A
Anton Zhilin, 2016-09-17
@Anton3

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 будет указывать на мусор :(
}

Simple structures usually do not indicate anything. We freely copy them and use them in the same way as we would use their component parts. The more complex the structure, the more likely it is that it cannot just be taken and moved to another area of ​​memory.

A
abcd0x00, 2016-09-18
@abcd0x00

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 question

Ask a Question

731 491 924 answers to any question