简体   繁体   English

函数返回结构中的错误

[英]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 = 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 im getting a error 在上面的代码中我收到错误

cannot convert amicable to amicable* in return 不能将友善转换为友善*

getAmicablePairs is declared to return a pointer to an amicable : 声明getAmicablePairs返回指向amicable的指针:

amicable *getAmicablePairs(...)

but you then try to return an amicable : 但您随后尝试返回amicable

return record;

rather than a pointer to one. 而不是一个指针。

Note that one "obvious" fix, which is to return a pointer to record : 请注意,一个“显而易见的”修复是返回指向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. 将不起作用,因为一旦getAmicablePairs返回,您将返回一个将要消失的变量的指针。 Instead you need to create a record using malloc and return that; 相反,您需要使用malloc创建一条记录并将其返回; something like this: 像这样的东西:

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

You'll need to change all your record. 您需要更改所有record. into record-> . 进入record->

Note also that you're writing into the amicablePair member of your structure without allocating it - that's going to cause a crash. 还要注意,您正在写入结构的amicablePair成员而不分配它-这将导致崩溃。 You need to malloc the amicablePair as well as the amicable . 你需要mallocamicablePair还有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." 然后通过“ record->”而不是“ record”进行访问。

Note: With the above approach you will need to free() the above allocation when you are finished with it. 注意:使用上述方法时,您需要在完成分配后释放()以上分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM