简体   繁体   中英

C Returning an array from a function

And having some trouble grasping arrays in C and how to return them via a function. If I do something like this

int main()
{
     int num_set[10]={0,1}; //initialize first two elements as 0,1 and rest as 0
     int* p=num_set;             //assign array to int pointer called p
     printf("\n%i",&num_set);    //outputs 2686660 on my machine
     printf("\n%i",&num_set[0]); //also outputs 2686660
     printf("\n%i",p);           //also outputs 2686660
     printf("\n%i",p[1]);*       //outputs 0; the same as num_set[1]
 }

It works as expected, but when I try to return an array through another function like the following

int multiply_by_2(int given_number)
{
     int num_set[10];
     for(int fun_counter=0; fun_counter<10; fun_counter++)
     {
          num_set[fun_counter] = (given_number*2) ;
     }
     return num_set;  //return int array num_set to caller
}

int main()
{
     int* p = multiply_by_2(300)    //assign array returned by function to p
     for(int main_counter=0; main_counter>10; main_counter++)
     {
          printf("\np[%i] = %i"
                 , i, p[i]);
     }
}

I get an error saying "invalid conversion from 'int' to 'int*'"

They was no error when I assigned the array to an int pointer in the first code, but I get this error when I try to return it through a function.

Please help.

In C you cannot return array by value. You would have to return the pointer of the array you want to return.

Pass a pointer and a size for a buffer to store your results.

This is wrong on so many levels, but the compiler error comes from your declaration of "multiply_by_2". You declare it to return an integer, but then you try to return a pointer.

Let's try something like this:

int* multiply_by_2(int size, int given_number)
{
     int *ip = (int*)malloc(size*sizeof(int)); // dynamically create int x[size]
     for(int fun_counter=0; fun_counter < size; fun_counter++)
     {
          ip[fun_counter] = (given_number*2) ;
     }
     return ip;  //return int array num_set to caller
}

Caller must free() returned memory.

int main(int argc, char **argv) {
    int *ip = multiply_by_2(3, 2);
    // ip points to array {4, 4, 4}
    free(ip);
    return 0;
}

We say that the function caller becomes owner of returned memory, that's why you are responsible to call free() later.

There are a number of errors here.

  1. The return type of the function multiply_by_2 needs to be int* - ie a pointer to an integer. What is actually returned is a pointer to the first element of the array.

  2. You are attempting to return a variable initialized on the stack ( num_set ). This will disappear as soon as the multiply_by_two function exits, because it is an automatic variable . Instead, you should use the malloc function to allocate heap memory. Here's a link explaining the difference between stack and heap memory

  3. You have a > where you should have a < in the for loop in main . As written the loop will immediately exit.

  4. Minor point - the number 10 is repeated several times throughout the code. It is better practice to use a variable or a #define to give the number a meaningful name

Here's an amended version of the code:

#include <stdio.h>
#include <stdlib.h> //This is required to use malloc

#define ARRAY_SIZE 10

int* multiply_by_2(int given_number)
{
    int *num_set =malloc(sizeof(int)*ARRAY_SIZE);
    for(int fun_counter=0; fun_counter<ARRAY_SIZE; fun_counter++)
    {
        num_set[fun_counter] = (given_number*2) ;
    }
    return num_set;  //return int array num_set to caller
}

int main()
{
    int* p = multiply_by_2(300);    //assign array returned by function to p
    for(int i=0; i<ARRAY_SIZE; i++)
    {
         printf("\np[%i] = %i", i, p[i]);
    }
    free(p);
}
int multiply_by_2(int given_number) // not returning an array, but just an int

The return type of your function is int therefore you will get an error when trying to assign it to int * . Change it to the following:

int* multiply_by_2(int given_number)

This change is acceptable because in C, an array of int s is interchangeable with a pointer to an int .

Your header is wrong. Should be
int* multiply_by_2(int given_number)
You need to return pointer of int, not just int.

Another thing, in the function multiply_by_2 you have created local array. That means that the array will be deleted after the function will end. You must use dynamic allocation (malloc and free).

Three major problems in your program:

  • The return type of function is int but you are returning an int * type.
  • You are returning the pointer to an automatic local variable.
  • Second expression in for loop in main would not let the body of loop to execute.

Change return type of the function to int * and use dynamic allocation.

int* multiply_by_2(int given_number)
{
     int* num_set = malloc(sizeof(int)*10);
     // rest of you code
}

And finally change second expression in your for loop in main to main_counter < 10 . Use free in main to free the allocated memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM