0

So basically I'm trying to write a method that returns two times the length of an array, but I cannot figure out how to make the length into an int so that it can be used. I have been trying to figure out the correct method to use since sizeof() returns the number of bytes, not the length of the array. What method should I be using and how can I fix this? Here is my code:

int main(int argc, const char * argv[]) {
    int arr[] = {1,2,3,4,5};
    cout << getLen(arr);
    return 0;
}

int getLen( int *arr ){
    int len = sizeof(arr);
    return 2 * len;
}

3 Answers3

2

I think this could be an XY problem. Ultimately if you want this kind of behaviour in C++ you should use an std::vector object. For example:

#include <iostream>
#include <vector> // Remember to include this

int getLen(std::vector<int> &vec) // Pass vec by reference rather than as a pointer
{
    return static_cast<int>(vec.size()) * 2; // Use .size() to get the number of elements in vec
    // ^^^ .size() returns a value of type size_t which is converted to an int using static_cast<int>
}

int main()
{
    std::vector<int> vec = {1,2,3,4,5};

    std::cout << getLen(vec);

    return 0;
}
Toggy Smith
  • 330
  • 2
  • 7
  • Good answer. However, your code generates: "warning: conversion from ‘std::vector::size_type’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion] " Trivial fix: You can use static_cast to convert the size_t to int. – 2785528 Apr 09 '20 at 19:15
  • @2785528 Hmmm I didn't get a warning for that when compiling in Visual Studio 2019 but nevertheless I've edited the answer. Thanks for pointing it out. – Toggy Smith Apr 09 '20 at 20:25
1
#include <iostream>

template<typename T,std::size_t n>
std::size_t get_new_len(T (&a)[n]) {
    return n*2;
}

int main() {
    int a[10] = {0};
    std::cout << get_new_len(a) << "\n";
}

you can do it in this way, using template argument deduction. output is 20

0

The result of sizeof(arr) is not the same in the main as in the function, i don't understand why , but it works like this :

int getLen(int *arr, int arrSize)
{
    int len = arrSize / sizeof(int);

    return len;
}

int main(int argc, const char * argv[])
{
    int arr[] = { 1, 2, 3, 4, 5 };

    cout << getLen(arr,sizeof(arr));

    return 0;
}
Toggy Smith
  • 330
  • 2
  • 7
wal
  • 1
  • 1