views:

262

answers:

3

I have a struct of type Duplicate I have a variable of type int called stringSize, it has a value of 5 I am creating a dynamic array:

Duplicate *duplicates;
duplicates = new Duplicate[stringSize - 1];

Later I delete[] duplicates;

I'm getting one member in that array only? I've verified that stringSize - 1 = 4 with a debug walk through. What can I do to get the 4 members I need?

Any help appreciated, Thanks // :)

+3  A: 
Duplicate *duplicates;
duplicates = new Duplicate[stringSize - 1];

Indeed gives you duplicates[0-3] (Assuming stringSize - 1 is 4, like you say). How are you determining you're getting less?

I suspect you may be doing something like: sizeof(duplicates) / sizeof(duplicates[0]), and on an off-change getting one. The above code only works for statically allocated arrays, where sizeof(duplicates) would match the size of the array, in bytes. In your case, it'll simply return the size of a pointer on your system. (duplicates is a Duplicate*)

And mandatory: Use std::vector if this is "real" code.


Your debugger is doing the best it can. As far is it's concerned, you've merely got a pointer to some data. Consider:

Duplicate foo;
Duplicate *duplicates_A;
duplicates_A = &foo; // points to one Duplicate

Duplicate *duplicates_B;
duplicates_B = new Duplicate[4]; // points to memory containing 4 Duplicate's

bar(duplicates_A);
bar(duplicates_B);

void bar(Duplicate* p)
{
    // is p a pointer to one value, or is it an array?
    // we can't tell, and this is the same boat your debugger is in
}

How should the debugger, just given a pointer, know if it's pointing to an array or just one value? It cannot, safely. (It would have to determine, somehow, if the pointer was to an array, and the size of that array.)

GMan
Debug walkthrough in XCode is showing only 1 member? I'm stymied? Got to be something I'm missing?
Spanky
Totally right! Thanks // :)
Spanky
I was too late with my response...
Cellfish
@Spanky: No problem. @Cellfish: :P
GMan
+1  A: 

You can't use sizeof to determine the size of a dynamic array. In fact, there isn't a standard API to determine the size of a dynamic array.

Use std::vector if you need to access the size.

KennyTM
A: 

If you use a debugger to view the elements you get, the problem may be that the type of your variable is Duplicate* which is just a pointer (which in C happens to also be an array but the type is just a pointer to one instance of Duplicate.

Cellfish