Thread: Make an array the same as an array from a function

  1. #1
    Registered User
    Join Date
    Nov 2020
    Posts
    14

    Make an array the same as an array from a function

    Hey,
    I have a function that returns an array that contains all the digits of a number
    Code:
    int seperation(int number){
        int arrayOfDigits[SIZE];
        int i = SIZE - 1;
        int lastDigit;
        while(number!=0){
            lastDigit = number % 10;
            arrayOfDigits[i] = lastDigit;
            i--;
            number /= 10;
        }
        return(arrayOfDigits);
    If i want to make an array that I have in my main function to be the same as the arrayOfDigits that is in this function what do i have to do?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,712
    The simplest thing to do is
    Code:
    void seperation(int number, arrayOfDigits[SIZE]){
        int i = SIZE - 1;
        int lastDigit;
        while(number!=0){
            lastDigit = number % 10;
            arrayOfDigits[i] = lastDigit;
            i--;
            number /= 10;
        }
    }
    That is, you pass in the array of where you want the result to be stored.

    This gives the caller the best opportunity to decide where to store the result, and saves all the complication that the called function would have to deal with when trying to return an array.
    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. Replies: 11
    Last Post: 10-20-2019, 02:00 PM
  2. make an array to point to another array
    By Dave11 in forum C Programming
    Replies: 4
    Last Post: 03-04-2014, 04:17 AM
  3. Replies: 12
    Last Post: 07-31-2013, 12:15 AM
  4. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  5. Replies: 11
    Last Post: 09-22-2006, 05:21 PM

Tags for this Thread