You are here:

C++/size of an array

Advertisement


Question
QUESTION: Hello Zlatko;
Is there any function in C++ that can calculates the summation of some values?
I have some constants like A(1),A(2)...A(n) that n and A(j) for j=1..n , will be introduced at the beginning of the program. But n may be different for various data that each time I'll give them to the program.
Now, I want to build an array like this:   
int array[b];          b=sum of A(j) | j=1..n
How can I do that?

ANSWER: Hello Amir.

As far as I know, there is no function to sum the contents of an array. It is a simple matter to build one using a loop, as I'm sure you know.

int sum(int* pArray, int size)
{
  int result = 0;
  for(int ix = 0; ix < size; ++ix) result += pArray[ix];
  return result;
}

The idea of making an array based on a size determined at runtime is not possible with the current C++ standard. I think it will be in the next release of the language. Until then, you need to do this:

int b = sum(A, n);
int* myArray = new int[b];

I hope that helps you out.

Best regards
Zlatko

---------- FOLLOW-UP ----------

QUESTION: Dear Zlatko;
Thanks for your guidance. But as far as I know the size of an array must be a constant integer number. I think "b" in the above structure that you write it, is a variable. Isn't it?

Answer
Yes, you are correct that the size of an array must be an integer constant, and yes, 'b' is a variable. That is why the array is being allocated with "new". It is correct to say

new int[b];

I believe you wanted and array whose size is calculated at runtime. Please let me know if I misunderstood your question.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.