我有一個函數返回一個指針,我正在計算給定數字的階乘。如何以C語言返回指針
這是框架代碼,我不能改變
#include<stdio.h>
#include<string.h>
//Read only region start
char* factorial (int input1)
{
//Read only region end
//Write code here
}
我寫的代碼是:
我嘗試這個代碼太
#include<stdio.h>
#include<string.h>
//Read only region start
char* factorial (int input1)
{
//Read only region end
//Write code here
char fact=1;
while(input1!=0)
{
fact = fact * input1;
input1--;
}
return fact;
}
左邊說了問題和右側是我寫的代碼。 它拋出的錯誤是「段錯誤」
該方案不需要main()
功能導致其東西mettl使用在後臺調用函數和評估結果。
'char * fact = 1;'聲明一個指針並將指針(地址)設置爲1,而不是發佈代碼的圖片,請直接複製粘貼到您的問題 – litelite
好吧,給我一分鐘 –
'由於您試圖訪問內存中的地址「1」,因此對「* fact + input」的引用將成爲段錯誤。你需要分配一個有效的地址來放入'fact',然後你可以正確引用它。 – lurker