Thread: sizeof

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    29

    Question calculating sizeof dynamic array

    Hi @all

    I was trying to learn dynamic allocation of arrays. I wrote easy program. Can someone tell me why I can't print out all integers in my array.

    Thanks

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
    	const int sentinel=-9;
    
    	int *arrPtr= new int[];
    
    	int in;
    
    	int i=0;
    
    	cout <<"Enter integers"<<endl;
    
    
    		cin >>in;
    
    		while (cin.good()&&(in!=sentinel))
    		{
    			arrPtr[i]=in;
    			i++;
    			cin>>in;
    			
    		}
    	
    	
    	for (int m=0; m<(sizeof (arrPtr)/sizeof (arrPtr[0])); m++)
    		
    		cout <<arrPtr[m]<<" ";
    	
    	cout <<endl;
    
    	return 0;
    }
    Code:
    input:
    1
    2
    3
    
    output:
    1  :confused:
    Last edited by Apropos; 03-24-2005 at 12:27 PM.
    Not to know, not to learn is shame

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > int *arrPtr= new int[];
    I've no idea how many integers you wanted to store.

    Perhaps
    int *arrPtr= new int[10];

    But if you don't know in advance how many you need, then consider a different data structure, say for an example an STL vector.

    > for (int m=0; m<(sizeof (arrPtr)/sizeof (arrPtr[0])); m++)
    This only works on REAL arrays actually in scope. It doesn't work on pointers to arrays, or pointers initialised with new.
    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
    Dec 2004
    Posts
    29
    Hi Salem

    When I don't know the size of array, do I have to use STL vektor. I don't want to use STL vector because I don't know.

    Is there another way to count how many elements I have in my dynamic array?

    thanks
    Last edited by Apropos; 03-24-2005 at 12:43 PM.
    Not to know, not to learn is shame

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by Apropos
    Hi Salem

    When I don't know the size of array, do I have to use STL vektor. I don't want to use STL vector because I don't know.
    Lets say you allocate an initial chunk of memory to store 10 integers like Salem gave in his example. Furthermore, lets say you have filled all those 10 slots with values and still haven't encountered your sentinel value yet and have just read in your 11th integer from cin. At this point, in order to store the value just read, you would have to allocate another chunck of memory with a larger capacity, say 20 integers for example. You would then have to copy the 10 integers already stored in the memory pointed to by the old pointer into the memory pointed to by the new pointer. You would then need to delete the old memory and repoint your old pointer to the newly allocated memory. Only after all of this would you be able to store the 11th value you read in. You would need to do this reallocation each time you reached the current limit of how many ints you could store in the available memory.

    Using a vector makes all of this much simpler. All of the memory management is taken care of for you automatically behind the scenes when using a vector. Vectors are easy to use once you are used to them. The biggest problem you might have trouble with is the concept of iterators and how to loop through the container:

    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main()
    {
        vector<int> intVect;
        int temp;
        const int sentinel = -9;
    
        // Store all ints entered until user types in -9
        while( cin >> temp && temp != sentinel )
            intVect.push_back(temp);
    
        // Output all ints in vector
        for( vector<int>::iterator it = intVect.begin(); it != intVect.end(); ++it )
            cout << *it << ' ';
    
        cout << endl;
    
        return 0;
    }
    Quote Originally Posted by Apropos
    Is there any way to use sizeof for printing them?
    Code:
    (sizeof (arrPtr)/sizeof (arrPtr[0]));
    it returns 1 so I get only first value of first element.

    thanks
    No, sizeof on any pointer is independent of the number of bytes allocated for that pointer. You could have another int used to keep track of the number of values you have stored... something you incremented each time through the loop. You could then use that "size" value as part of your print loop conditional.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Quote Originally Posted by Apropos
    I was trying to learn dynamic allocation of arrays.

    When I don't know the size of array, do I have to use STL vektor. I don't want to use STL vector because I don't know.

    Is there another way to count how many elements I have in my dynamic array?thanks
    Dynamically allocating an array means that you don't specify the size until runtime. For a statically allocated array, you have to specify the size before the program starts running, i.e. at compile time. However, in both cases, you have to specify the array size.

    Let's say you know that no user will enter more than 50 numbers. You could statically declare your array like this:

    int input[50];

    However, if the user only enters 2 numbers, then you are wasting memory because the array could hold 48 more numbers. One solution is to dynamically allocate an array so that it's size is just equal to the number of int's the user will enter. In order to tailor the size of the array to a specific user, you have to ask the user how many numbers they will enter, so that you can dynamically allocate the requisite amount of memory. There isn't a way that you can not declare the array size--the computer has to know how much memory to allocate. Even vectors allocate a fixed amout of memory--it just happens behind the scenes, so it looks as if the vector has no fixed size.

    If you ask the user how many int's they will enter, then a different sized array can be dynamically allocated for each user. You just use the entered size when you allocate memory:

    int* p = new int[entered_size];

    In addition, you should delete any memory allocated with new to avoid memory leaks--it's one of the clean up chores necessary with C++(Java, for instance, deletes the memory automatically for you):

    delete [] p;

    If p points to an array, then you use brackets before the pointer name--otherwise you just use delete with the pointer name:

    delete p;

    It should be noted that you are not deleting the pointer variable--it will still exist, and you can assign another address to it. What you are deleting is the memory at the location where the pointer points to.
    Last edited by 7stud; 03-24-2005 at 08:22 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Malloc,calloc..Sscanf.
    By ozumsafa in forum C Programming
    Replies: 22
    Last Post: 07-26-2007, 01:09 AM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. finding size of empty char array
    By darsunt in forum C Programming
    Replies: 12
    Last Post: 05-30-2006, 07:23 PM
  4. Cutting up an std::string
    By Shamino in forum C++ Programming
    Replies: 26
    Last Post: 04-04-2006, 11:02 AM
  5. Model not showing up on screen...
    By Shamino in forum Game Programming
    Replies: 14
    Last Post: 03-09-2006, 08:00 PM