The member vetor
is part of the structure Firma
!
The compiler will return an error saying that vetor
was not declared if you try something like:
vetor[firma->qtdFuncionario]->nome /* ERRO! */
You need to tell the compiler that vetor
is inside firma
:
firma->vetor[firma->qtdFuncionario]->nome /* OK (?) */
CARING:
The compiler will compile this code perfectly, however, if your intent is to store the size of vetor
in qtdFuncionario
, the code yet has a problem!
Something like:
firma->vetor[firma->qtdFuncionario]->nome /* NÃO! */
Accesses an element after the last element of vetor
, reading an unknown memory position, probably causing in an undefined behavior code.
Accesses the first functionary of vetor
:
firma->vetor[ 0 ]->nome /* OK! */
Accesses the last functionary of vetor
:
firma->vetor[ firma->qtdFuncionario - 1 ]->nome /* OK! */
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char nome[100];
float salario;
} Funcionario;
typedef struct {
char nome[100];
unsigned int qtdFuncionario;
Funcionario *vetor;
} Firma;
int main( void )
{
unsigned int i;
Firma f;
/* Nome da Firma */
strcpy( f.nome, "FooBar" );
/* Quantidade de funcionarios */
f.qtdFuncionario = 3;
/* Aloca memoria para 3 funcionarios */
f.vetor = (Funcionario*) malloc( sizeof(Funcionario) * 3 );
/* Funcionario #1 */
strcpy( f.vetor[0].nome, "Fulano" );
f.vetor[0].salario = 1000.00;
/* Funcionario #2 */
strcpy( f.vetor[1].nome, "Ciclano" );
f.vetor[1].salario = 1200.00;
/* Funcionario #3 */
strcpy( f.vetor[2].nome, "Beltrano" );
f.vetor[2].salario = 1500.00;
/* Exibe lista de Funcionarios da Firma */
for( i = 0; i < f.qtdFuncionario; i++ )
{
printf("Funcionario #%d:\n", i+1 );
printf("\tNome: %s\n", f.vetor[i].nome );
printf("\tSalario: %.2f\n", f.vetor[i].salario );
}
/* Libera memoria */
free(f.vetor);
return 0;
}
Exit:
Funcionario #1:
Nome: Fulano
Salario: 1000.00
Funcionario #2:
Nome: Ciclano
Salario: 1200.00
Funcionario #3:
Nome: Beltrano
Salario: 1500.00
What do you mean "Compiler does not accept!" ?
– Lacobus