Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <iostream>

int addArray(int nums, int k){
    int temp = 0;
    for(int i = 0; i < sizeof(nums); i++){
        temp = temp * 10 + nums[i];
    }
    return temp + k;
}
int main()
{
    int nums1[] = {1,0,0,0};
    int res = addArray(nums1, 300);
    std::cout<<res;
}


What I have tried:

I'm trying to add array to integer but this error shows. What can i do?
Posted
Updated 12-Dec-22 1:39am
v2

Quote:
int addArray(int nums, int k){
This is wrong, because nums should be an array of integers (and, anyway, you need to pass the size of the array as well).

Try
C++
#include <iostream>

int addArray(int num[], size_t num_size, int offset)
{
  int temp = 0;
  for(size_t n = 0; n < num_size; ++n)
  {
    temp = temp * 10 + num[n];
  }
  return (temp + offset);
}

int main()
{
  int num[] = {1,0,0,0};

  int res = addArray(num, sizeof(num)/sizeof(int), 300);
  std::cout << res << std::endl;
}



Note, you might also write:
C++
#include <iostream>
#include <numeric>

int main()
{
  int num[] = {1,0,0,0};
  int result = 300 + std::accumulate( std::begin(num), std::end(num), 0, [](int a, int b){ return a*10 + b; });
  std::cout << result << std::endl;
}
 
Share this answer
 
v2
Comments
CPallini 12-Dec-22 8:05am    
Copy my code and try it.
Happy Sahu 12-Dec-22 8:07am    
thanks for giving your valuable time.
CPallini 12-Dec-22 8:53am    
You are welcome.
I think you first want loop through the array using the for loop.
Using just sizeof(array) will give the total size of the array in bytes, it won't give the lenght of the array. For that you need to also divide the result with sizeof the data type the array holds. In this case int.

So, the loop will be something like
C++
for(int i = 0; i< sizeof(nums)/sizeof(int); i++)


This should resolve your issue.
 
Share this answer
 
v2
Comments
Happy Sahu 12-Dec-22 7:39am    
it again gives the same error
in this line shows error
temp = temp * 10 + nums[i];
CPallini 12-Dec-22 7:44am    
That wouldn't work, because the array decays to pointer in the function call.
GKP1992 12-Dec-22 7:47am    
Gotcha. I missed the addArray definition.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900