[英]Returning Pointer from a function ( Variable is declared in the function)
int* sum(int *mypt,int len){
int i;
int mysum = 0;
for(i=0;i<len;i++)
mysum += mysum;
return &mysum; // I cannot do this since the function frame goes away after the call.
}
int main()
{
int *pt = (int*) malloc(3*sizeof(int));
pt[0] = 0;
pt[1] = 1;
pt[2] = 2;
int *s = sum(pt,3);
printf("%d\n",*s);
return 0;
}
我想返回一個指向mysum
的指針。 我不能做int static sum = 0
因為它是固定的。 我不能使用int const sum = 0
因為它給出了錯誤““ readonly”“。 有針對這個的解決方法嗎 ?
為什么需要從sum()
返回一個指針,您只可以按值返回答案。 如果必須返回一個指針,則需要在sum()
內malloc()
內存,並且sum()
的調用者必須free()
答案,但這不是很有效。
int sum(int mypt, len)
{
int i;
int mysum = 0;
for(i=0;i<len;i++)
mysum += mysum;
return mysum; // return the answer by value.
}
並如下更改main()
:
int main()
{
int *pt = (int*) malloc(3*sizeof(int));
pt[0] = 0;
pt[1] = 1;
pt[2] = 2;
int s = sum(pt,3);
printf("%d\n",s);
return 0;
}
是的,使用malloc
將整數放置在堆內存中並獲得一個指針。 然后可以從函數返回此指針:
int* sum(int *mypt, int len) {
int i;
int* mysum = malloc(sizeof(int));
//make sure you dereference (*) when you wish to work with the value.
*mysum = 0;
for(i=0; i<len; i++) *mysum += *mysum;
return mysum;
}
順便說一句,看來您的許多代碼已損壞。 這僅解決了如何返回指針!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.