1

I'm trying to make C a program to find the amicable numbers smaller than n.

Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number.

Example of amicable numbers (220, 284);for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.

Until now, I've calculated the sum of divisors of each number and I've put them into an array s;

s[0]=0, s[1]=1; s[2]=1+2=3, s[3]=1+3=4 and so on.

But my program crashes and there is nothing in the debugger. Everything is printed well , but after all there is returned -1073741819 and the program crashes.

#include <stdio.h>
#include <stdlib.h>
int sumofdivizor(int nr)
{
  //nr=number,s=sum of the divisors of nr
  int i,s=0;

  for(i=1;i<=nr;i++)
  {
    if(nr%i==0)
     {
      s=s+i;
      }
      else continue;
  }

  return s;
}

int main()
{
    int *s,n,i;

    s =(int*)malloc(n*sizeof(int));
    s[0]=0;
    printf("Print a limit number\n");
    scanf("%d",&n);
    for(i=1;i<n;i++)
    {
      *(s+i)=sumofdivizor(i);
    }
    for(i=0;i<n;i++)
      printf("s[%d]=%d\n",i,s[i]);

    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
AlexB.
  • 83
  • 6

1 Answers1

7
int *s,n,i;

s =(int*)malloc(n*sizeof(int));

You're using the value of n to decide how much space to allocate. But you haven't assigned any value to n yet.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Thank you, David! That was the problem. I've just learnt something about dynamically memory allocation and i don't know it so well. – AlexB. Dec 07 '15 at 10:40
  • @AlexB.: That's surprising. I'd rather expected you to have learned something about causality, or about the order of doing things, rather than about dynamic memory allocation. the actual `malloc` call is a total red herring in this question. – Kerrek SB Dec 07 '15 at 10:48