[問題] C回傳陣列指標
我寫一個簡單的要算2元一次方程式的程式
用一個函式來解出s,t的值,但我想把2個答案的陣列回傳出來
所以solve_funct函式回傳的是指標的位址
但我在main函式中從這個位址去讀值有點問題
想請問一下觀念是錯在哪裡
以下是我的程式碼
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
// func.s是未知數s的係數a1 func.t是未知數t的係數, c是常數
// a1*s + a2*t - c = 0
typedef struct func
{
float s;
float t;
float c;
}func;
// 解 det of matrix
float det(float a, float b, float c, float d){
float ans;
ans = a*d - c*b;
return ans;
}
// solve the intersection point for 2D plane
float* solve_funct(func f1,func f2){
float ans[2];
float a1,a2,a3;
a1 = det(f1.s,f1.t,f2.s,f2.t);
a2 = det(-f1.c,f1.t,-f2.c,f2.t);
a3 = det(f1.s,-f1.c,f2.s,-f2.c);
ans[0] = a2/a1;
ans[1] = a3/a1;
std::cout<<&ans<<"\n";
return &ans[0];
}
void main(){
// test solve
func f1,f2;
f1.s = 1;
f1.t = 1;
f1.c = -1;
f2.s = 1;
f2.t = -1;
f2.c = -1;
float *ans;
ans = solve_funct(f1,f2);
std::cout<<*(ans+0); //s解 但是這邊印出來的不是函式解出來的值..
std::cout<<*(ans+1); //t解
}
感謝您的耐心
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 76.180.212.189
推
04/26 16:32, , 1F
04/26 16:32, 1F
→
04/26 16:32, , 2F
04/26 16:32, 2F
→
04/26 16:33, , 3F
04/26 16:33, 3F
→
04/26 16:33, , 4F
04/26 16:33, 4F
→
04/26 16:33, , 5F
04/26 16:33, 5F
→
04/26 16:34, , 6F
04/26 16:34, 6F
→
04/26 16:34, , 7F
04/26 16:34, 7F
→
04/26 16:50, , 8F
04/26 16:50, 8F
推
04/26 17:35, , 9F
04/26 17:35, 9F
→
04/26 17:35, , 10F
04/26 17:35, 10F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章