2

recently i want to convert some codes from opencv to c#. But I have some problem in declaring the dynamic array in c++.

int* memorySteps = 0;
CV_CALL( memorySteps = new int [ 10*sizeof(memorySteps[0]) ]);    

I want to convert it to a normal c# int array. The problem is the length.In c++, the declaration above seems that the compilor will create an array with 40 int elements(coz the sizeof the type memorySteps[0] is 4, 4 bytes length.). Is my understanding correct? However, it doesnt make sense because actually in the algorithm I only need an array of 10 int elements. So can anyone give me a hint which is right in the following(in c#), or can anyone show me other examples:

int[] memorySteps =new int [10*sizeof(int)];

or

int[] memorySteps =new int [10];
2
  • Welcome to the wonderful world of finding bugs in someone else's code! Commented Mar 8, 2012 at 14:41
  • 2
    Yes, that C++ code doesn't make sense. Commented Mar 8, 2012 at 14:42

3 Answers 3

2

Your understanding is correct; the C++ version will create an array of 40 integers, assuming sizeof(int)==4. It may be that the author was getting mixed up with C's malloc, which takes a size in bytes.

So your first version will give the same behaviour, and the second is more likely to give the intended behaviour - but there is a danger that the extra-large buffer was hiding other bugs, which might suddenly be exposed if you reduce the size.

Sign up to request clarification or add additional context in comments.

1 Comment

I wrote a loop to check the length of the dynamic array. for(int n=0;memorySteps[n];++n ){} . the result of n should be (in my understanding) 40, but it returns the result of 44. It really confuses me.
2

If the algorithm needs ten items, then use

int[] memorySteps =new int [10];

I suspect that the C++ code was itself ported from C code, where the programmer called malloc, like this:

memorySteps = malloc(10*sizeof(memorySteps[0]));

Whoever converted that code to C++ has probably forgotten to take away the multiplier. This has resulted in a functionally correct, yet somewhat memory inefficient code (although wasting 30 bytes these days hardly even counts as inefficient).

Comments

0

What you need is:

int[] steps = new int [10];

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.