I can’t dynamically allocate a struct vector in C

Asked

Viewed 703 times

1

I don’t know why you can’t allocate!!

struct dados {
  int numero;
  char nome[5];
};
typedef struct dados Das;

void manipula_um_par (struct dados *a, int b) {
  a[b].numero = a[b].numero /2;
}

void manipula_pares(struct dados *x, int w) {
  int z;
  for (z = 0; z < w; z++) {
    if (x[z].numero % 2 == 0) {
      manipula_um_par(x,z);
    }
  }
}

int main()
{
  Das *p;
  int k;

  printf("Qual sera o numero de alunos?\n");
  scanf("%d",&k);

  p = (Das*)malloc(k*sizeof(Das));
  Das v[p];

  int x;
  for (x = 0; x < k; x++) {
    printf("\nDigite o nome do %d aluno: ", x+1);
    scanf("%s", v[p].nome);
    printf("\nDigite o %d numero: ", x+1);
    scanf("%d",&v[p].numero);
  }

  manipula_pares(v, k);

  for (x=0; x < k; x++) {
    printf("--- %d ", v[p].numero);
  }

  return 0;
}
  • 1

    p is a Pointer for a data structure and therefore cannot serve as an input for an array in Das v[p].

  • then what should I do to be able to allocate this vector of structs??

  • the vector you have already managed to allocate is the Das *p. Excludes the Das v[] of your code and in its place uses the p with a maximum rate of k - 1.

1 answer

1


Original program corrected.

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

struct dados {
  int numero;
  char nome[5];
};
typedef struct dados Das;

void manipula_um_par (struct dados *a, int b) {
  a[b].numero = a[b].numero /2;
}

void manipula_pares(struct dados *x, int w) {
  int z;
  for (z = 0; z < w; z++) {
    if (x[z].numero % 2 == 0) {
      // manipula_um_par(x,z); // errado
      manipula_um_par(&x[z], z);
    }
  }
}

int main()
{
  Das *p;
  int k;

  printf("Qual sera o numero de alunos?\n");
  scanf("%d", &k);

  p = (Das*)malloc(k*sizeof(Das));

  // erro, tamanho nao e' constante...
  // mas essa declaracao nao faz sentido mesmo, e' desnecessaria
  // Das v[p];

  int x;
  for (x = 0; x < k; x++) {
    printf("\nDigite o nome do %d aluno: ", x+1);
    // scanf("%s", v[p].nome); // <---- nao faz sentido
    scanf("%s", p[x].nome);
    printf("\nDigite o %d numero: ", x+1);
    // scanf("%d",&v[p].numero); // nao faz sentido
    scanf("%d", &p[x].numero);
  }

  // manipula_pares(v, k); // nao faz sentido
  manipula_pares(p, k);

  for (x = 0; x < k; x++) {
    // printf("--- %d ", v[p].numero); // nao faz sentido
    printf("--- %d ", p[x].numero);
  }

  return 0;
}

Browser other questions tagged

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