0

I am currently studying coding in C language and I have doubts about the return of functions, what I am trying to do is the following:

  1. Call the number () function and pass 3 values ​​of the integer type to it.

  2. The number () function takes these values ​​and inserts them into an array of type integer and returns.

  3. The main function stores the return in a variable of the integer type and prints at the end of the numbers according to the index of the array that I define.

What am I doing wrong in my coding?

    #include <stdio.h>
    #include <stdlib.h>

    int number(int a, int b, int c);

    int main()
    {
        int n1 = 10;
        int n2 = 20;
        int n3 = 30;

        int myReturn = number(n1, n2, n3);

        printf("%i \n", myReturn[1]);
    }

    int number(int a, int b, int c)
    {
        int number[3] = {a, b, c};
        return number;
    }

Thank You

0

You can't return an array in C. You end up returning the address of the local array, which then gets assigned to your myReturn variable.

0
0

I found this example, really cool.

The function has been converted to a pointer.

    int * onefunction()
    {
        static int returnA[2];
        returnA[0] = 1;
        returnA[1] = 2;

        return returnA;
    }

    void main()
    {
        int *callfunc;
        int a, b;
        callfunc = onefunction();
        a = callfunc[0];
        b = callfunc[1];
    }

Thank You

0

You are trying returning the local variable address that going to destroy at end of function because int myarray[3] here myaray is pointer to a continues memory location not int you can check it by,

int main()
{
  int myarray[3] = {0};

  if(myarray == &myarray[0])
  {
     printf("Yup ! same");
  }

  return 0;
}

So what is way to do that just return the variable that memory allocated on heap like either dynamically or with help of static like,

// static way
int *number(int a, int b, int c)
{
   // this going to be allocated on heap
   static int myarray[3];
 
   myarray[0] = a;
   myarray[1] = b;
   myarray[2] = c;

   return myarray;
}
#include <stdlib.h>

// dynamically
int* number(int a, int b, int c)
{
  int *myarray = calloc(3, sizeof(int));
 
  if(myarray == NULL)
  {
    return NULL;
  }
  else
  {
    myarray[0] = a;
    myarray[1] = b;
    myarray[2] = c;

    // must be freed manually
    return myarray;
  }
}
// main
int main()
{
  int *myarray = number(1,2,3);

  printf("%d %d %d", myarray[0], myarray[1], myarray[2]);

  //uncomment if dynamic allocation
  //free(myarray);
 
  return 0;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .