繁体   English   中英

如何在代码中动态分配向量和结构?

[英]How to dynamically allocate vector and struct in a code?

我试图在下面的代码中分配一个结构和一个数组,但我不知道如何进行。 我试图在不添加其他库的情况下执行此操作。 它是葡萄牙语的,所以如果你不明白它的意思,我很抱歉。

struct RegistroAluno{
    int Matricula;
    char Nome[20];
    int AnoNascimento;
};

int main()
{
    int QuantidadeAlunos;
    
    printf("Quantos alunos serão armazenados?\n");
    scanf("%i", &QuantidadeAlunos);
    
    struct RegistroAluno P1[QuantidadeAlunos];
    struct *P1=(int *)malloc(QuantidadeAlunos*sizeof(struct));

    for(int i=0; i<QuantidadeAlunos; i++){
        printf("Qual a matrícula do aluno?\n");
        scanf("%i", &P1[i].Matricula);
    }/* I gotta do the same to all the other elements of the struct*/
    
    
    return 0;
}

我正在尝试分配一个结构和一个数组

您在此处分配struct RegistroAluno的可变长度数组 (VLA):

    struct RegistroAluno P1[QuantidadeAlunos];

或者,您可以像这样动态分配数组:

    struct RegistroAluno *P1 = malloc(QuantidadeAlunos*sizeof(*P1));

这里是包含和错误处理的完整程序:

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

struct RegistroAluno{
    int Matricula;
    char Nome[20];
    int AnoNascimento;
};

int main(void) {
    printf("Quantos alunos serão armazenados?\n");
    int QuantidadeAlunos;
    if(scanf("%i", &QuantidadeAlunos) != 1) {
        printf("scanf failed\n");
        return 1;
    }
    if(QuantidadeAlunos < 1) {
        printf("QuantidadeAlunos must be > 0\n");
        return 1;
    }
    struct RegistroAluno *P1 = malloc(QuantidadeAlunos*sizeof(*P1));
    if(!P1) {
        printf("malloc failed\n");
        return 1;
    }
    for(int i=0; i<QuantidadeAlunos; i++){
        printf("Qual a matrícula do aluno?\n");
        if(scanf("%i", &P1[i].Matricula) != 1) {
            printf("scanf failed\n");
            return 1;
        }
    }
}

和示例 session:

Quantos alunos serão armazenados?
2
Qual a matrícula do aluno?
3
Qual a matrícula do aluno?
4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM