Thread: length of array

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    30

    length of array

    I have an array with an unknown number of elements and want to know ne number of entries.
    Here's my code:
    Code:
    #include <iostream>
    #include <cmath>
    #include <cstdio>
    
    
    using namespace std;
    
    
    class nvec{
    
    
    	private:
    		double *a;
    		int length;
    
    
    	public:
    		nvec(int size, double*p)
    		{
    			length = size;
    			a = new double [length];
    			for(int i = 0;i<length;i++)
    			{
    				a[i] = p[i];
    			}
    		}
    		//~nvec();
    		double Len(void);
    };
    double nvec::Len(void)
    {
    double length = sizeof(a)/sizeof(double);
    return length;
    }
    int main()
    {
    double t[]={2.,9.,12.,1.,113.};
    nvec A(sizeof(t)/sizeof(double),t);
    A.Print();
    cout<<" :"<<A.Len()<<endl;
    return 0;
    }
    However, I only get 1 as the length of the array. I guess this is because sizeof gives me just the memory of one entry.
    What would be the correct way to accomplish what I try?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,600
    Just delete line 32, and return the local member variable you calculated at line 20.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    30
    It's working. Thanks for your help.

  4. #4
    Registered User
    Join Date
    Mar 2016
    Posts
    13
    Note that sizeof(array) returns the total size of array in bytes only if the array is statically allocated. For dynamically allocated arrays, the sizeof() only gives you the size of pointer.

  5. #5
    Registered User
    Join Date
    Jun 2017
    Posts
    156
    BTW. In C++ raw pointers shouldn't be used. There are much better alternatives like vector 0d smart pointers.

  6. #6
    Registered User
    Join Date
    Feb 2018
    Posts
    4
    You have write 32 line in your program is wrong, rectify that one only.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Length of an array
    By papyka in forum C Programming
    Replies: 3
    Last Post: 07-07-2016, 01:10 AM
  2. str length of int array
    By Sorinx in forum C Programming
    Replies: 12
    Last Post: 11-24-2012, 07:44 AM
  3. c++ array length?
    By corbinc in forum C++ Programming
    Replies: 2
    Last Post: 11-07-2009, 02:11 PM
  4. Getting the length of an array
    By Pharao in forum C Programming
    Replies: 24
    Last Post: 09-05-2008, 01:53 PM
  5. length of an array
    By chrismiceli in forum C Programming
    Replies: 8
    Last Post: 02-27-2003, 11:18 PM

Tags for this Thread