D
D
DartNyan2016-02-14 14:28:13
C++ / C#
DartNyan, 2016-02-14 14:28:13

How to return an array?

Hello.
I'm writing a function that takes an array, looks for the minimum elements on even lines, and places them in a vector. Those. "placement" should take place in f-ii and this vector should be returned.
The problem is (I think) when trying to return an array.
I want to do it in two ways. The first is by passing the address of the array (I pass the array that I process and the array with the result to the function, I return the address of the array with the result, is it also possible?), The second method is with memory allocation. Later.

spoiler
#include <stdio.h>
#include <stdlib.h>
#define n 3 //Столбцы
#define m 4 //Строки

int main()
{
    //Функция, которая находит минимальные элементы массива на четных сроках и размещает их в вектор
    int array[m][n] = {{3,9,2}, // +
                       {3,2,1},
                       {5,1,2}, // +
                       {4,2,6}};
    int minArr[m/2]; // Вектор для вывода размера m/2

    int search_min_elements_of_array(int array[][3], int *minArr);
    {

    int k = 0;          // Переменная, которая увеличивается на четных строках

    for (int j = 0; j < m; j++)                   // Перебор строк

            if (j % 2 == 0) {                     // Если строка четная
                int min = array[j][0];
                for (int i = 1; i < m - 1; i++) { // Перебор элементов строки
                    if (min > array[j][i])
                        min = array[j][i];
                        minArr[k] = min;
                }
                k++;
            };

    return *minArr; // Как вернуть массив?
    } // End of function

    int minArray[m/2] = search_min_element_of_array(int array[][3], int *minArr);
    for (int k = 0; k < m/2; k++)
        printf(" %i", minArray[k]);


}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Александр Ручкин, 2016-02-14
@DartNyan

Зачем вам его возвращать?
В Си++ нельзя передать массив по значению (только если он не составная часть структуры), вместо этого передают указатель на первый элемент массива, как у вас. Соответственно, все изменения, который вы проводите над int * minArr внутри search_min_elements_of_array отражаются на массиве int minArr[m/2], и отдельно что-то возвращать не надо.
Также стоит перенести определение (тело) функции search_min_elements_of_array за пределы (перед) main, ну и вызов у вас неверный:

// int minArray[m/2] = search_min_element_of_array(int array[][3], int *minArr); // больше похоже на объявление функции
search_min_element_of_array(array, minArr);

A
AtomKrieg, 2016-02-14
@AtomKrieg

I don't see C++ in your code, it's written in C. If you need to return an array from a function in C++:

auto search_min_elements_of_array(/*in*/) -> std::vector<int>
{
    std::vector<int> ret;
    //...
    return ret;
}

J
jcmvbkbc, 2016-02-14
@jcmvbkbc

int search_min_elements_of_array(int array[][3], int *minArr);

and then the body of the "nested function", and even further its call is cool (:

A
abcd0x00, 2016-02-20
@abcd0x00

An example of passing a pointer to a function and returning it from a function

The code
#include <stdio.h>

int *func(int a, int b, int *p)
{
    p[0] = a;
    p[1] = b;
    return p;
}

int main(void)
{
    int arr[4], *p;

    p = func(1, 2, arr);
    printf("%d %d\n", p[0], p[1]);

    p = func(3, 4, arr + 2);
    printf("%d %d\n", p[0], p[1]);

    p = arr;
    printf("%d %d %d %d\n", p[0], p[1], p[2], p[3]);
    return 0;
}

Вывод
[[email protected] c]$ .ansi t.c -o t
[[email protected] c]$ ./t
1 2
3 4
1 2 3 4
[[email protected] c]$

Just in your situation at you misunderstanding of pointers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question