开发者

error in function returning structure

#include<stdio.h>
#include "amicablenumber.h"

int i,j;
struct amicable         
{
    int **amicablePair;
    int size;
};

main()
{

int startnum = 250;
int endnum =开发者_Python百科 1000;
struct amicable* ami;

ami = getAmicablePairs(startnum, endnum);   

printf("{");
for(int i = 0; i<ami->size; i++)
{
printf("{%d, %d}",ami->amicablePair[i][0], ami->amicablePair[i][1]);
}
printf("}");
}

amicable *getAmicablePairs(int startnum,int endnum)
{
    int size=0;
    int sumfactors(int);
    amicable record;
 for(i=startnum;i<=endnum;i++)
 {
 for(j=endnum;j>=startnum;j--)
 {
 if((sumfactors(i)==j)&&(sumfactors(j)==i) && (i!=j))
 {
  record.amicablePair[size][0]=i;
  record.amicablePair[size][1]=j;

  size++;
 }}}
 record.size=size;
 return record;
 }

  int sumfactors(int number)
 {
 int sum=0;
 for(i=1;i<number;i++)
 {
 if(number%i==0)
 sum +=i;
 }
 return sum;
 }

in the above code i m getting a error

cannot convert amicable to amicable* in return


getAmicablePairs is declared to return a pointer to an amicable:

amicable *getAmicablePairs(...)

but you then try to return an amicable:

return record;

rather than a pointer to one.

Note that one "obvious" fix, which is to return a pointer to record:

return &record;

won't work, because you'd be returning a pointer to a variable that was about to go away as soon as getAmicablePairs returns. Instead you need to create a record using malloc and return that; something like this:

amicable *record = (amicable*) malloc(sizeof(amicable));

You'll need to change all your record. into record->.

Note also that you're writing into the amicablePair member of your structure without allocating it - that's going to cause a crash. You need to malloc the amicablePair as well as the amicable.


You are returning an (amicable *) - a pointer to an amicable, but your function creates an (amicable) (not a pinter to one).

Instead of declaring

amicable record;

you need to do this (or an equivalent):

amicable *record = (amicable *) malloc(sizeof(amicable));

and then access via "record->" rather than "record."

Note: With the above approach you will need to free() the above allocation when you are finished with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜