-2

I got a problem with the memset funciton Here is part of the code Code1

int main()
{
    long long int num=600851475143;
    bool factor[5000];
    //memset(factor,true,sizeof(factor));
    primer_factor_find(factor);
    int largest=largest_primer_factor(num,factor);
    cout<<largest<<endl;  
    return 0;
}

void primer_factor_find(bool factor[])
{
    memset(factor,true,sizeof(factor));
    int j,k;
    for(j=1;j<=2500;j++)
        for(k=3*j+1;k<=5000;k+=(2*j+1))
            factor[k]=false;
}

the only difference between Code2 is the location of the memset function.(In Code2,memset is in the main) I find Code1 doesn't work at all.Code2 works fine.What's the matter?

Pawn Pod
  • 63
  • 1
  • 8
  • http://stackoverflow.com/questions/5493281/c-sizeof-a-passed-array – AnT stands with Russia Aug 20 '15 at 03:52
  • http://stackoverflow.com/questions/27096272/using-sizeof-on-an-array-passed-to-a-function – AnT stands with Russia Aug 20 '15 at 03:52
  • Also note that `memset()` really operates at the byte level, but `bool` is not the same thing. You could use `std::fill()` instead, which will result in similar code, but is safer. – Dietrich Epp Aug 20 '15 at 03:53
  • i think in order to work memset properly in your function "primer_factor_find" you need to mention size of the array explicitely. Because sizeof(factor) will return size of pointer. – aashoo Aug 20 '15 at 03:55
  • 2
    According to this Meta discussion: http://meta.stackoverflow.com/a/266246/578749 this question shouldn't be marked as duplicate. The causes of the problem are the same, but the question and perceived symptoms are different. – lvella Aug 20 '15 at 04:01

3 Answers3

3
void primer_factor_find(bool factor[])
{
    memset(factor,true,sizeof(factor));

passing unbounded array into function basically equal to pointer. At this point, sizeof give you the pointer size, and leave most of the content garbage.

Whereas you put that to main, the compiler knows the full size.

Non-maskable Interrupt
  • 3,841
  • 1
  • 19
  • 26
1

In the function signature the array is converted to a pointer bool *, and so sizeof factor will return sizeof(bool *).

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
1

factor decays to a pointer here void primer_factor_find(bool factor[])

Arrays decays to pointers when they are passed to a function.

Nishant
  • 1,635
  • 1
  • 11
  • 24