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 within firma
:
firma->vetor[firma->qtdFuncionario]->nome /* OK (?) */
CAUTION:
The compiler will perfectly compile this code, however, if your intent is to store the size of vetor
to qtdFuncionario
, the code still has a problem!
Something like:
firma->vetor[firma->qtdFuncionario]->nome /* NÃO! */
Access a element after the last element of vetor
, reading an unknown memory location, probably leading to an undefined behavior code.
Access the first official of vetor
:
firma->vetor[ 0 ]->nome /* OK! */
Access the last official 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;
}
Output:
Funcionario #1:
Nome: Fulano
Salario: 1000.00
Funcionario #2:
Nome: Ciclano
Salario: 1200.00
Funcionario #3:
Nome: Beltrano
Salario: 1500.00