Thread: being dumb again

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    13

    Thumbs down being dumb again

    I stumble on some simple prime generator implementation in basic C, it was supposed to be something like function returning array of size_t values:

    Code:
    size_t *  primeGen(size_t _MAX_)
    {
        size_t primes[_MAX_];
        int PrimeIndex = 2;
    
    
        primes[0] = 2; primes[1] = 3;
    
    
        for (size_t p = primes[1] ; p < _MAX_  ; p = p + 2)
        {
            int isPrime = 1;
            
            for (size_t j = 1 ; j < primes[PrimeIndex] / 2 ; ++j )
            {
    
    
                if (p % primes[j] == 0) isPrime = 0; 
                
            }
            
            if (isPrime) 
                {
                    primes[PrimeIndex] = p ; PrimeIndex++ ;
                }
    
    
        }return primes[PrimeIndex];
    }
    Code:
    error: invalid conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘size_t*’ {aka ‘long unsigned int*’} [-fpermissive]
    Tried to force casting size_t* on that return but it also doesn't work. Idk but I just keep forgetting everything about C, feels easier to do things in Cpp with vectors and strings modules etc.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > return primes[PrimeIndex];
    The basic problem is you can't return an array.

    This would fix the syntax error.
    return primes;

    But the problem is, your array goes out of scope by the time the caller gets to look at the data.

    Code:
    void primeGen(size_t _MAX_, size_t primes[_MAX_])
    You make the caller pass in a suitable sized array for you to fill in.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dumb this down
    By les2012 in forum Tech Board
    Replies: 5
    Last Post: 12-09-2012, 09:13 AM
  2. am I dumb?
    By Carp in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 01-30-2003, 06:42 PM
  3. I am so dumb
    By face_master in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 11-09-2002, 09:04 PM
  4. Was I really that dumb?
    By face_master in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 09-14-2002, 08:02 PM
  5. Im new and dumb :)
    By Prodigy in forum C++ Programming
    Replies: 1
    Last Post: 05-04-2002, 11:27 AM

Tags for this Thread