Why doesn't my add function add all the numbers? [duplicate] - c++

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 8 years ago.
I am using sizeof trick to get the length of array, but it only looks like it's adding 1 and 2.
#include <iostream>
#include <stdio.h>
using namespace std;
int add(int array[])
{
int sum = 0;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i += 1)
{
sum += array[i];
}
return sum;
}
int main()
{
int array[4] = {1, 2, 3, 4};
cout << add(array);
return 0;
}
Output is 3. What is wrong?

In a parameter to a function, int array[] is another way of saying int *array, so sizeof(array) will return the size of a pointer-to-int. I’m pretty sure there’s a more idiomatic C++ way of doing this, particularly in the newer versions of C++, but the C way of dealing with this would be to pass a second parameter with the size of the array.

Related

My code is not running because of abrupt core dump(segmentation fault) [duplicate]

This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
Closed 2 months ago.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void converter(vector<char>keypad[],int num[], int index, string result, int size_of_num){
if(index == size_of_num){
cout << result << " ";
return;
}
int digit = num[index];
int size_of_keypad = keypad[digit].size();
for(int i=0; i < size_of_keypad; i++){
converter(keypad, num, index + 1, result + keypad[digit][i], size_of_num);
}
}
int main(){
vector <char> keypad[] = {
{},{},{'a','b','c'},
{'d','e','f'},
{'g','h','i'},
{'j','k','l'},
{'m','n','o'},
{'p','q','r','s'},
{'t','u','v'},
{'w','x','y','z'}};
int numbers[] = {2,3,4};
int size_of_num = sizeof(numbers);
converter(keypad, numbers, 0, string (""), size_of_num );
return 0;
}
I tried running this code, which was to transfrom phone numbers into words. I used vector in this problem with a reucrsive function. But I am not sure if its just the memory overflowing or just totally something else.
I tried and search online in order to solve this and I found the correct code, but everything they were doing was the same and the only thing that was differnt were the varible names. I just couldn't figure out whats wrong.
you calculate size wrong
int size_of_num = sizeof(numbers);
should be
int size_of_num = sizeof(numbers)/ sizeof(numbers[0])
or even
int size_of_num = std::size(numbers);

Why does this code outputs two different results? [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 1 year ago.
I'm trying to make a function that returns the length of an array, but the function always returns 8
#include <iostream>
using namespace std;
int size(int arr[])
{
return sizeof(arr);
}
int main()
{
int v[] = {1, 2, 4};
cout << sizeof(v) << endl;
cout << size(v);
return 0;
}
This is because ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’..

"Variable cannot be used as a constant" c++ array [duplicate]

This question already has answers here:
How to create a dynamic array of integers
(8 answers)
Closed 2 years ago.
I am struggling with C++. I learned Java before and i think it is much easier, tbh. Currently, I am trying to code a counting sort algorithm with c++. I want to get the maximum of my array to declare my helping array with the size = maximum +1; I tried several ways but nothing works. It always shows "variable cannot be used as a constant". I also have found a code which does the same as mine but seems like to work. Can anyone give me some hints or solutions?
Thanks in advance.
#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
int getMax(int arr[], int size)
{
int max = arr[0];
for (int i = 1; i < sizeof(arr); i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
void countingSort(int *arr, int size)
{
int max = getMax(arr, size);
int hilfsArr[max + 1];
}
For array of dynamic size, just use std::vector, something like:
void countingSort(int *arr, int size)
{
std::vector<int> counter(*std::max_element(arr, arr + size));
// ...
}
You can not use variables for compile time array size simply because compiler has no way of knowing what the value returned by your getMax function will be ...
You need to use dynamic arrays in cases like this...
void countingSort(int *arr, int size)
{
int max = getMax(arr, size);
int *hilfsArr=new int[max + 1]; // allocate
... here put the rest of your code for this function
delete[] hilfsArr; // free before exiting function
}

How can I solve this problem with arrays in C++?

I am working on the Edabit challenge: Get arithmetic mean of the given array. Now I have code like that:
#include <iostream>
int data;
using namespace std;
int mean(int data);
int main()
{
int data[] = { 1, 2, 3, 4 };
cout << mean(data);
}
int mean(int data)
{
double mean = 0;
for (int i = 0; i < sizeof(data) / sizeof(data[0]); i++)
{
mean += data[i];
}
mean /= sizeof(data) / sizeof(data[0]);
}
and I am stuck. I use Visual Studio 2019 on Windows 7 Professional, and I have underlined 3 characters ( data[i], and 2x data[0]). For this x Visual Studio says expression must have pointer-to-object type (Error E0142) and I have no idea what it means with this. I only know what pointer is.
In Visual studio I added the return statement, but while shortening the code here for publishing I forgot to add it. Otherwise, this wasn't the actual problem. Now I mustn't add it in the question because the comments would be wrong. The comments are related to the upper question, but my real question (for future readers stuck on this problem) is rather:
How to pass array as an argument in the function.
Now, that I am more proficient in C++, I know the terminology and how to state it, and I also know that this isn't so clear to a total beginner: you can't just write f(int[] arr) (you can't pass arrays), but you have to write f(int* arr) (you can pass a pointer that points on that array). At that time I couldn't just search it because I didn't know much of C++ terminology.
Arrays decay into pointers (an int* in this case) when passed as argument to functions. Your mean function only accepts one single int.
When the array decays into a pointer the size information is lost. You can however prevent that by defining a function that accepts arrays of the exact type and size you need. This can be done with templates:
#include <iostream>
template<typename T, size_t N>
double mean(const T (&data)[N]) {
double sum = 0;
for (size_t i = 0; i < N; ++i)
{
sum += data[i];
}
return sum / N;
}
int main()
{
int input[] = { 1, 2, 3, 4, 5, 6, 7 };
std::cout << mean(input) << '\n';
}
If you don't want to use templates (or only accept arrays of a certain size), you need to pass the size information on to the function manually:
#include <iostream>
#include <iterator> // std::size
double mean(const int* data, size_t N)
{
double sum = 0;
for (size_t i = 0; i < N; ++i)
{
sum += data[i];
}
return sum / N;
}
int main()
{
int input[] = { 1, 2, 3, 4, 5, 6, 7 };
std::cout << mean(input, std::size(input)) << '\n';
}
Your mean function, well, is mean.
1. It doesn't return a value; there is no return statement.
2. It uses variable name the same as the function (not a recommended coding style).
3. There is a global variable data that is hidden by a local variable data inside main.
4. You're confusing the compiler and the reader: the global data variable is a single int. The local variable in main is an array of int.
You should have the last line be:
return mean;

C++: passing and returning pointers to arrays - code not working [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 7 years ago.
I'm trying to write a function that casts an array of ints into doubles. It takes in a constant pointer to the original int[] array (to avoid unwanted modifications?) and returns a pointer to an array of casted double[]. However, the code that I wrote doesn't seem to be working. Can anyone point out what's wrong with it?
#include <iostream>
using namespace std;
double* castToDouble(const int *input);
int main(){
int integers[] = {1,2,3,4};
double *doubles = castToDouble(integers);
cout << "numElements in doubles: " << sizeof(doubles)/sizeof(double) << endl;
for(int i = 0; i < sizeof(doubles)/sizeof(double); i++){
cout << doubles[i] << endl;
}
return 0;
}
double* castToDouble(const int *input){
// Obtain the number of elements in input.
int numElements = sizeof(input)/sizeof(int);
double *doubleAry = new double[numElements];
cout << "numElements in input: " << numElements << endl;
for(int i = 0; i < numElements; i++){
doubleAry[i] = static_cast<double>(input[i]);
}
return doubleAry;
}
The output of the program is the following:
numElements in input: 2
numElements in doubles: 1
1
The numElements' calculated seem to be arbitrary too. I'm pretty new to c++ and am unable to pinpoint the problem. Thanks in advance.
As you marked it C++, I thought this might be more idiomatic:
#include <vector>
#include <algorithm>
std::vector<double> CastToDouble(std::vector<int> const & ints)
{
auto doubles = std::vector<double>(ints.size());
std::transform(ints.begin(), ints.end(), doubles.begin(), [](int value) -> double {
return static_cast<double>(value);
});
return doubles;
}
int main(int argc, char* argv[])
{
auto values = std::vector<int>() = {
1, 2, 3, 4
};
auto doubles = CastToDouble(values);
}