0

This is a problem I've been struggling with for a while now. The codes I have tried below are not compiling either.

The question is: How do I differentiate between a pointer and a fixed array in a function parameter?

// Concepts for the Array I have tried but not succeeded.
template <size_t length, typename type>
const unsigned int len(type arg[static length]) { return length; }

template <size_t length, typename type>
const unsigned int len(type(&)[length]) { return length; }

// This works for Arrays & Pointers
// but should be less prioritized over the function that detects the Array
template <typename type> const unsigned int len(type* arg) { return sizeof(*arg); }

I know how arrays & pointers are basically similar when passed into a function, but it asks the question: is there not a way to tell them apart?

Syntactically yes, but otherwise what other way is there?

Anyway, thanks for reading through and cheers on your response.

1
  • 2
    static length is not valid C++. That particular C99 feature is not available. Commented Nov 21, 2018 at 6:30

2 Answers 2

1

This approach works for me:

#include <stdio.h>

template<typename T, int size> unsigned int len(const T(&)[size]) {printf("The number of items in your array is:  %i\n", size); return size;}
template<typename T> unsigned int len(const T * p) {printf("The size of the item your pointer points to is: %zu\n", sizeof(*p)); return sizeof(*p);}

int main(int, char **)
{
   int myArray[10];
   int * myPointer = myArray;

   (void) len(myArray);
   (void) len(myPointer);

   return 0;
}

... when I run it, it prints out:

The number of items in your array is:  10
The size of the item your pointer points to is: 4
Sign up to request clarification or add additional context in comments.

Comments

1

The length of an array can only be deduced if the array is passed by reference, otherwise it decays to pointer:

template<typename T, std::size_t length>
constexpr std::size_t len(const T(&)[length]) { return length; }
//                               ^^^

template<typename T>
constexpr std::size_t len(const T *&p) { return sizeof *p; }
//                                ^^^

Full demo:

#include <cstdlib>

template<typename T, std::size_t length>
constexpr std::size_t len(const T(&)[length]) { return length; }

template<typename T>
constexpr std::size_t len(const T *&p) { return sizeof *p; }

#include <iostream>
int main(int, char **)
{
    const int array[7] = {};
    const int *pointer = array;

    std::cout << "array has " << len(array) << " items\n"
              << "and pointer is to " << len(pointer) << " chars\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.