user906357
user906357

Reputation: 4685

getting size of array from pointer c++

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.

Here is the function header:

int largest(int *list, int highest_index)

How can I get the number of integers in the array 'list'.

I have tried the following methods:

int i = sizeof list/sizeof(int); //returns incorrect value
int i = list.size(); // does not compile

Any help will be greatly appreciated!

Upvotes: 33

Views: 135744

Answers (8)

Jan Bancerewicz
Jan Bancerewicz

Reputation: 1

Instead of trying to return a new array, created inside of the function you can create it outside and pass it as a reference.

void modifyTabOfPointers(int size, int* number, Node* neighbours[6])
{
    int counter=0;
    //Node* neighbours[6];
    // instead of creating array inside function, we pass it as argument
    for (int i = 0; i < size;i++){
        if (!(neighbours[i]->visited)){
            neighbours[i]->visited = true;
            counter++;
        }
    }
    *number = counter;
}

Initialization in main():

int counter = 0;
Node* neighbours[6];
getNeighbours(size, &counter, neighbours);

Upvotes: 0

Miguel Tom&#225;s
Miguel Tom&#225;s

Reputation: 1911

There a really good solutions by BM Monjur Morshed to determine the size of an array from a pointer as follows:

    #include <bits/stdc++.h>
    using namespace std;

    int main()
    {
    int ara[] = {1, 1, 2, 3, 5, 8, 13, 21};
    int size = *(&ara + 1) - ara;
    cout << “This array has “ << size << “ elements\n”;
    return 0;
    }

Output:

This array has 8 elements

one can find a full explanation on this medium.com article below:
https://medium.com/@bmqube/find-size-of-an-array-using-pointer-hack-in-c-c-2c1c6743e12e

Upvotes: -1

kfsone
kfsone

Reputation: 24249

C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array is a pointer, it just means that it can decay to one.

void func(int* ptr);

int array[5];
int* ptr = array; // valid, equivalent to 'ptr = &array[0]'
func(array); // equivalent to func(&array[0]);

This last part is the most relevant to your question. You are not passing the array, you are passing the address of the 0th element.

In order for your function to know how big the incoming array is, you will need to send that information as an argument.

static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);

Because the pointer contains no size information, you can't use sizeof.

void func(int* array) {
    std::cout << sizeof(array) << "\n";
}

This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.

Instead you need to accept the size parameters

void func(int* array, size_t arraySize);

static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);

Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:

void func(int array[5]);

http://ideone.com/gaSl6J

Remember how I said that an array is NOT a pointer, just equivalent?

int array[5];
int* ptr = array;

std::cout << "array size " << sizeof(array) << std::endl;
std::cout << "ptr size " << sizeof(ptr) << str::endl;

array size will be 5 * sizeof(int) = 20

ptr size will be sizeof(int *) which will be either 4 or 8 bytes.

*sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that.

If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write:

sizeof(array) / sizeof(array[0])

or

sizeof(array) / sizeof(*array)

Upvotes: 48

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

Pointers do not have information about the number of elements they refer to. If you are speaking about the first argument of the function call then if list is an array you can indeed use the syntax

sizeof( list ) / sizeof( int )

I would like to add that there are three approaches:

  1. use arrays passed by reference
  2. use pointer to the first element and the number of elements.
  3. use two pointers - the start pointer and the last pointer as standard algorithms usually are defined. Character arrays have an additional possibility to process them.

Upvotes: 4

rekredhead
rekredhead

Reputation: 1

My answer uses a char array instead of an integer array but I do hope it helps.

You can use a counter until you reach the end of the array. Char arrays always end with a '\0' and you can use that to check the end of the array is reached.

char array[] = "hello world";
char *arrPtr = array;

char endOfString = '\0';
int stringLength = 0;

while (arrPtr[stringLength] != endOfString) {
stringLength++;
}
stringLength++;
cout << stringLength << endl;

Now you have the length of the char array.

I tried the counting the number of integers in array using this method. Apparently, '\0' doesn't apply here obviously but the -1 index of the array is 0. So assuming that there is no 0, in the array that you are using. You can replace the '\0' with 0 in the code and change the code to use int pointers and arrays.

Upvotes: -1

Sai Nikhil
Sai Nikhil

Reputation: 1237

The simple answer is you cannot. You need to store it in a variable. The great advantage with C++ is it has STL and you can use vector. size() method gives the size of the vector at that instant.

#include<iostream>
#include<vector>
using namespace std; 
int main () {
    vector<int> v;
    for(int i = 0; i < 10; i++) {
        v.push_back(i);
    }
    cout << v.size() << endl;
    for(int i = 0; i < 10; i++) {
        v.push_back(i);
    }
    cout << v.size() << endl;
    return 0;
}

output:
10
20

Not tested. But, should work. ;)

Upvotes: 4

igleyy
igleyy

Reputation: 605

You need to remember in a variable array size, there is no possibility to retrieve array size from pointer.

const int SIZE = 10;
int list[SIZE];
// or
int* list = new int[SIZE];  // do not forget to delete[]

Upvotes: 2

john
john

Reputation: 87944

There's no way to do that. This is one good reason (among many) to use vectors instead of arrays. But if you must use an array then you must pass the size of the array as a parameter to your function

int largest(int *list, int list_size, int highest_index)

Arrays in C++ are quite poor, the sooner you learn to use vectors the easier you will find things.

Upvotes: 11

Related Questions