Home > Software engineering >  How to retrieve an array from a pointer in c
How to retrieve an array from a pointer in c

Time:02-03

I'm having problems with a program that only accepts arrays. I'm having plenty of pointers to different arrays, but using *p seems to only give me the first element of the array. I want to return all the elements of the array. I know the length of the array, if that helps.

#include <typeinfo>

#include <iostream>

int i[10];
int* k=i;

cout<<typeid(i).name()<<'\n';

cout<<typeid(*k).name()<<'\n';

results in 'int [10]' and 'int' respectively. I want some way of returning k as 'int [10]'.

CodePudding user response:

Example to show you how much more convenient C array/vector is then "C" style arrays with pointers :

#include <vector>
#include <iostream>

// with std::vector you can return arrays
// without having to think about pointers and/or new
// and your called cannot forget to call delete
std::vector<int> make_array()
{
    std::vector<int> values{ 1,2,3,4,5,6 };
    return values;
}

// pass by reference if you want to modify values in a function
void add_value(std::vector<int>& values, int value)
{
    values.push_back(value);
}

// pass by const refence if you only need to use the values
// and the array content should not be modified.
void print(const std::vector<int>& values)
{
    // use range based for loops if you can they will not go out of bounds.
    for (const int value : values)
    {
        std::cout << value << " ";
    }
}

int main()
{
    auto values = make_array();
    add_value(values, 1);
    print(values);
    std::cout << "\n";
    std::cout << values.size(); // and a vector keeps track of its own size.

    return 0;
}

CodePudding user response:

Your k is a pointer to int. It points to the first element of the array. If you want a pointer to the whole array then you need to declare it as such.

#include <typeinfo>    
#include <iostream>
int main() {
    int i[10];
    int* k=i;
    int(*p)[10] = &i;


    std::cout<<typeid(i).name()<<'\n';
    std::cout<<typeid(*k).name()<<'\n';
    std::cout<<typeid(*p).name()<<'\n';
}

Output:

A10_i
i
A10_i

However, as others have said, std::array is much less confusing to work with. It can do (almost) anything a c-array can do without its quirks.

Certainly there is a solution to your actual problem that does not require to get the array from a pointer to a single integer.

  • Related