我无法从子程序打印最终数组

时间:2015-05-15 16:09:19

标签: c arrays subroutine

我需要创建一个可以对N个向量求和并打印最终数组的程序,但是例如,如果我把N = 2,第一个数组(a,b)和第二个数组(c,d)的总和应该是(a + c,d + b)但它只显示我(a,b)并给我一个错误。当然你只能在真实程序中使用数字,所以请给我一些帮助,以便在这段代码中找到问题。谢谢。 PS:有些引用是葡萄牙语,我很抱歉,但这是我的母语。

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


/*Program that calculate the sum of N float vector, 
by using a subroutine that generate a resultant vector*/


//SUBROTINA
void forca_res(float vet_res[2],float vet[2],int num)
{   
    int i;
    //Calculo do Vetor Resultante
    for(i=0;i<2;i++)
    {
        vet_res[i] = vet_res[i] + vet[i];
    }
}


//PROGRAMA PRINCIPAL
int main(void)
{
    //Declaracao de variaveis
    int num, dim=2, i, cont=0;
    float *vet_res, *vet;
    vet= (float*) calloc( dim, sizeof(int) );
    vet_res = (float*) calloc( dim, sizeof(int) );

    //Leitura de dados
    printf("Type the number 'N', of the force vectors: ");
    scanf("%d", &num);

    //Logic
    while (cont != num)
    {
        printf("\nType the elements of the vector:\n");
        for(i=0;i<2;i++)
        {
            scanf("%f", &vet[i]);
        }
        //Chamando a Subrotina
        forca_res(vet_res, vet, num);
        free(vet);
        cont++;
        printf("\nYour resultant vector:\n");
        for(i=0;i<2;i++)
        {
            printf("%f ", vet_res[i]);
        }
    }

    //Imprimindo o Resultado
    printf("\n\nVETOR RESULTANTE:\n");
    for(i=0;i<2;i++)
    {
        printf("%f", vet_res[i]);
    }

    //Finalizando o Programa
    printf("\n\nFim do Programa!\n");
    getch();
    return 0;
}

1 个答案:

答案 0 :(得分:4)

你不应该在你的while循环之后释放vet,否则第二次循环,INSERT INTO SecondTable (`keyid`, `proyect`) SELECT `keyid`, `proyect` FROM `tasks` LIMIT 1 将被取消分配。

相关问题