Returning pointer to dynamically created int array from function

This is a discussion on Returning pointer to dynamically created int array from function within the C Programming forums, part of the General Programming Boards category; I am trying to return a pointer to a dynamically created array of ints from a function. Right now the ...

  1. #1
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153

    Returning pointer to dynamically created int array from function

    I am trying to return a pointer to a dynamically created array of ints from a function. Right now the array values should be the same as their index. so data[3] = 3.... Eventually this array will be filled with primes from some sieve code that I have already written, but I need to get this function framework working. It currently compiles without warning, but seg faults. Thanks to dwks who wrote nearly all of this code.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int *getPrimes(int *count, int max)
    {
            int size = 10;  // this keeps track of how many elements are allocated
            int *array = malloc(size * sizeof(*array));
            *count = 0;  // this keeps track of how many elements are used, so *count <= size at all times
    
            int x;
            for( x = 0 ; x < max ; x++ )
            {
                    // assume x needs to be added to the array.
                    if(*count + 1 > size)
                    {
                            // not enough space.
                            size *= 2;
                            array = realloc(array, size * sizeof(*array));
                    }
            array[*count] = x;
            *count ++;
            }
        return array;
    }
    
    
    
    int main(void)
    {
            int n = 300;
            int count;
            int *data = getPrimes(&count, n);
            printf("data0 is %i", data[0]);
    
            return 0;
    }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    A couple of things.

    1. checking realloc return.
    Code:
    size_t newSize = size * 2;
    void *temp = realloc(array, newSize * sizeof(*array));
    if ( temp != NULL ) {
        array = temp;
        size = newSize;
    } else {
        // realloc failed, so array/size are preserved
        // free it, exit, whatever
    }
    2. *count ++;
    Check your operator precedence.
    You want (*count)++ to increment what count points to.

    > if(*count + 1 > size)
    Or perhaps
    if(*count >= size)
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,310
    Instead of this:
    Code:
    *count ++;
    You probably intended to write:
    Code:
    ++*count;
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    That did it. Although I'm just not sure why. What does *count++ do? Why doesn't it increase the value of what count points to?

    If you're busy don't worry about it, it works, now I just have to graft in the sieve code and I'm good to go.

  5. #5
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    Oh, where are my manners, thank you very much Laserlight

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,310
    Quote Originally Posted by javaeyes
    What does *count++ do? Why doesn't it increase the value of what count points to?
    It increments the value of count, not what count points to
    Oh, and you're welcome!
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Code:
    *count++;
    is the same as
    Code:
    *(count++); /* the de-reference is ignored, just as if you had a statement "42;" */

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,425
    To clarify a bit on why your original code, and Salem's and Laser's code work the way they do:

    C Operator Precedence Table

    Take a close look. The postfix ++ has higher precedence than the prefix ++ or dereference (unary *). That means it happens before the dereference, so
    Code:
    *count++
    // and
    *(count++)
    are effectively the same, but what you wanted is to dereference first, then increment:
    Code:
    (*count)++
    which is what Salem suggested.

    Laserlight's suggestion of moving the ++ to a prefix/preincrement has the same effect, so
    Code:
    ++*count
    //and
    ++(*count)
    are effectively the same. That's because of the operator associativity. Note that prefix ++ and dereference have the same precedence. So which one do we do first? Prefix operators (which are inherently unary) are among the few that are actually right-to-left associative. Meaning you evaluate the expression from right to left.

    It can get a bit more complicated when you have long expressions with operators that have both R-to-L and L-to-R associativity. Keeping track of what is going on can be tough, especially if you don't have the table fully memorized. That's why I always recommend to use parentheses to ensure you get the order you want (but don't overdo it). If you want to increment what count points to, then put what count points to in parentheses (*count) and increment that. Then it doesn't matter whether use use prefix or postfix increment, and you don't have to worry so much about operator precedence and associativity.

  9. #9
    Registered User javaeyes's Avatar
    Join Date
    Feb 2012
    Posts
    153
    That helps a lot, seeing it from a viewpoint of precedence makes it clearer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing multiple pages of dynamically created Websites
    By Quarlash in forum C Programming
    Replies: 11
    Last Post: 07-07-2009, 04:21 PM
  2. Replies: 0
    Last Post: 05-29-2009, 05:48 AM
  3. Replies: 6
    Last Post: 01-16-2007, 08:21 PM
  4. Dynamically adding method to created controls
    By earth_angel in forum Windows Programming
    Replies: 4
    Last Post: 06-26-2005, 07:11 PM
  5. Avoiding leaks on dynamically created data members
    By Mario in forum C++ Programming
    Replies: 13
    Last Post: 06-01-2002, 11:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21