Vector size in C

Asked

Viewed 1,600 times

0

I am new to the C language and am getting problems to determine the size of vectors of the struct type.

Example. I have a category type structure with three types of variables 1 int and 2 char.

#include <stdio.h>
#include <stdlib.h>


struct categoria_st{
    char nome_categ[25];
    int num_subcateg;
    char subcateg_st
};

Now, I intend to create a dynamic vector of the struct type categorias_st through a question within the main function. I thought of something like:

int main(){
struct categoria_st cat;
int n_categ;



   printf("Quantas categorias queres adicionar?\n");
    scanf("%d", &n_categ);
    return 0;

}

However, I don’t know how to accomplish this in the C language.

2 answers

1

#include <stdio.h>
#include <stdlib.h>


struct categoria_st{
  char nome_categ[25];
  int num_subcateg;
  char subcateg_st;
}

int main(){
  int n_categ;
  //primeiro pedir ao utilizador o numero de categorias
  printf("Quantas categorias queres adicionar?\n");
  scanf("%d", &n_categ);

  //neste momento já podes declarar a variável do tipo da estrutura definida
  //com o valor pretendido pelo utilizador
  struct categoria_st category[n_categ];

  return 0;

}

Initially a structure is created called categoria_st, consisting of 3 variables nome_categ, num_subcateg, subcateg_st.

In the main a variable is declared n_categ of the whole type to store the size of the categories to be inserted.

This value is saved to the address of the variable n_categ through the scanf().

Then a array of the so-called structure Category with the size inserted by the user.

  • could explain what your code does? how it answers the question? texts help in understanding.

  • I tried to explain in text what was in the code by comments... I think that here what the user intended was to initialize an array of the structure initially defined with a size indicated by the user, and that’s what I put in the code... @Erloncharles

0


I’m not the best person to answer, but I’m learning from it.

Below is a step by step example I was testing on repl it.

First we created the struct here the identifier is s_products

struct s_produtos
{
  int codigo;
  char nome[20];
};

We defined two variables of the type int

// Recebera o valor informado pelo usuário
int qnt = 0;
// A cada loop guardara a posição no qual sera adicionado
// o produto
int posicao = 0;

Reads the keyboard input and stores the value entered in qnt

printf("Quantas produtos deseja adicionar?:");
scanf(" %d", &qnt);

We create the variable protudos of the kind s_produtos and define its size with the value of qnt

struct s_produtos produtos[qnt];

We loop and the user is asked to inform the data.

for(posicao; posicao < qnt; posicao++) {
  printf("\n");
  printf("Informe o código:");
  scanf("%d", &produtos[posicao].codigo);
  flush_in();// Limpa o teclado
  printf("Informe o nome:");
  // Usei gets pois scanf para no espaço e não pega a linha toda, ex:
  // Leite em Pó
  // Só retorna: Leite
  gets(produtos[posicao].nome);

}

The function flush_in found in the Sopt for scanf(" %d", &produtos[posicao].codigo); wasn’t working.

void flush_in() {
    int ch;
    do {
        ch = fgetc(stdin)
    } while (ch != EOF && ch != '\n');
}

Below we show the records on the screen

// Armazena o tamanho total do vetor
int total = sizeof(produtos)/sizeof(produtos[0]);
printf("\n\n");
printf("+--------- PRODUTOS ---------+\n");
for(int i = 0; i < total; i++) {
  printf("%d - %s\n", produtos[i].codigo, produtos[i].nome);
}
printf("+----------------------------+\n");

You can see it working in repl it..

Reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.