0

After finally getting introduced to programming through Python, I decided to start coding using C. Right now I am on project euler, and I am trying to solve problem 3 using memory allocation to fit an array in. I am well aware that there are tons of easier ways to do this however I would like to know how to do it this way to expand my knowledge. Whenever I run this code, I get very strange numbers for some reason. Can someone tell me how to do this concept? It is not too much code, it might seem long because I like to make alot of space. I would like to add that when i use numbers like 45 or 50 it is fine. It starts acting up when using the number in the problem which is 600851475143.

Thank you in advance!

#include <stdio.h>

int newprim_fac(long long int n){

    int index=0;
    int i=2;
    long int MAXSIZE=100;
    int*W=(int*)calloc(1,MAXSIZE);

    while(n!=1){

        if(n%i==0){

            while(n%i==0){
                printf("\n\n           %d", i);
                n=n/i;
                W[index]=i;
                index++;
            }
        }
        i++;
        if(sizeof(W)>=MAXSIZE){
            *W=(int*)realloc(W,2*MAXSIZE);
        }
    }

    printf("\n\nsize of W is: %d\n", sizeof(W));

    for(i=0;i<sizeof(W);i++){
        printf("\n\n%d", W[i]);
    }

    free(W);
    return 0;
}
Omar
  • 33
  • 7
  • 1
    Please don't cast the return of `malloc` and family - see [this question](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) for a discussion why – UnholySheep Jan 16 '17 at 07:50
  • 1
    also `*W=(int*)realloc(W,2*MAXSIZE);` is wrong - you are dereferencing the pointer first and then storing the returned value of `realloc` in it. You probably wanted to do `W=realloc(W,2*MAXSIZE);`? – UnholySheep Jan 16 '17 at 07:53
  • 1
    And `int*W=(int*)calloc(1,MAXSIZE);` looks like the parameters are wrong. Or did you intend to allocate only a single element of size `MAXSIZE`? `int*W=calloc(MAXSIZE,sizeof(int));` would seem more like what you intended to do – UnholySheep Jan 16 '17 at 07:56
  • As for why the code is "acting up" - the mistakes I pointed out are causing your code to invoke *undefined behavior*. – UnholySheep Jan 16 '17 at 07:59
  • Hello Unholy Sheep, thank you so much for all your help. I read through the discussion you pointed out and that was very helpful. It gave me the right answer almost instantly, even after i added code to only print out the largest factor. Thank you so much! – Omar Jan 16 '17 at 09:29

0 Answers0