Size of a vector of characters according to their addressing

1

Is the size of a character vector given by its address or variable value? Example:

char[1000] = "Exemplo Teste"

Is the length of this variable 1KB due to its char[1000] address or its size is 13 because of its content?

    
asked by anonymous 26.12.2018 / 21:40

2 answers

2

The terms are wrong but for what you want to know the answer is that there is a reserve of space of 1000 bytes in memory. Although this is an implementation detail, all existing implementations will be reserved in stack .

Note that this is not 1KB, at least not in the way people know. Until strictly speaking, because 1 KB actually has 1000 bytes, but when people use KB they actually want to use KiB which is the equivalent of 1024 bytes.

Remembering that you can only enter 999 characters if you want to follow the string string pattern, this because of the terminator .

The declaration of the variable (in the part in parentheses) determines this placeholder and the assignment is effectively taking up space.

    
26.12.2018 / 21:54
0

Friend, from what I saw in the comments what you want to know is if when you do this:

char vetor[20000];

This space is automatically saved in memory for this vector.

Well, the primitive char type holds 1 byte per character, ie if you make a vector with 20000 of space, this vector will save 20000 of memory space for it to use. That means: every time you start the program this vector will take that space of 20000 bytes and store them regardless of their content. To avoid making such a large vector size without necessity you can do a dynamic allocation of space through the malloc function, so every time you start the program the function allocates that space dynamically, saves it, and when you finish and program identify or free:

vetor = (char *) malloc(20000*sizeof(char));
.
.
.
.

free(vetor);

It will release all unused space, leaving the program lighter. I hope that was the doubt.

    
29.12.2018 / 00:27