[英]I cannot print the final array from the 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;
}
在您的while循环之后,您不应该释放vet
,否则,直到第二遍循环,才会分配vet
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.