This question already has answers here:
Passing Arrays to Function in C++
(5 answers)
What is array to pointer decay?
(11 answers)
Closed 7 months ago.
What is the difference between taking as a function argument an int pointer or an int array in C++?
void arrayFunction1(int * x) {
for(int i = 0; i < 10; i++) {
cout << x[i] << endl;
}
}
void arrayFunction2(int x[]) {
for(int i = 0; i < 10; i++) {
cout << x[i] << endl;
}
}
int main() {
int dstdata[10];
arrayFunction1(dstdata);
arrayFunction2(dstdata);
return 0;
}
Both results look the same to me.
There are completely identical. In a function parameter int x[] is just another way of writing int* x. Even int x[10] is the same (the 10 is completely ignored).
Now why Kernighan and Ritchie (the inventors of C) thought this piece of deception was a good idea is another question. I guess they weren't thinking of all the people who have to learn the syntax.
Related
This question already has answers here:
Length of array in function argument
(9 answers)
Find the Size of integer array received as an argument to a function in c [duplicate]
(4 answers)
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 1 year ago.
I'm trying to pass an array as a pointer to a function, but when I do that the function only sees the pointer as an array with 1 variable.
Here is my code:
void make3(int* a) {
int n = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n; i++) {a[i] = 3;}
}
int main()
{
int a[3] = { 0, 1, 2 };
make3(a);
int* b = a;
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
cout << *(b + i) << endl;
}
}
The function make3 only changes the first value of the array to 3, instead of all of them.
Is this normal?
If not, what am I doing wrong?
When you pass an array to a function, it decays to a pointer.
int n = sizeof(a) / sizeof(a[0]);
Gets evaluated to
int n = sizeof(int*) / sizeof(int);
Which is 1 (when sizeof(int*) is 4 - depends on inplementation).
You should pass the array size as an argument instead:
void make3(int* a, int n) {
for (int i = 0; i < n; i++) {a[i] = 3;}
}
int main()
{
int a[3] = { 0, 1, 2 };
make3(a, 3);
for (int i = 0; i < 3; i++) {
cout << a[i] << endl;
}
}
If you can’t add that argument, use std::vector:
#include <vector>
void make3(std::vector<int> &a) {
for (int i = 0; i < a.size(); i++) {a[i] = 3;}
}
int main()
{
std::vector<int> a{ 0, 1, 2 };
make3(a);
for (int i = 0; i < a.size(); i++) {
cout << a[i] << endl;
}
}
Is this normal?
Yes.
In C++, an array will decay to a pointer at any opportunity. C++ inherited this convenience behavior from C.
It makes thinking about arrays as-if they were the same as pointers. But they are not.
In C++ a pointer can point to nothing (nullptr), or point to an object, or point to an array of objects. The pointer is oblivious of whether it points to an object or an array of objects.
(Or be dangling, or be uninitialized, or be some arbitrary value. These should be avoided.)
If not, what am I doing wrong?
You are not using std::vector.
Since, in the comments, you say that you cannot use a std::vector, then you'll need to pass in the length of the array as a std::size_t parameter along with a pointer to the array.
But you also say you cannot pass in the length of the array. So then you will need to use an array reference rather than a pointer.
Also, C++17 has std::size(a) which can be used instead of sizeof(a)/sizeof(a[0]).
#include <cstddef>
#include <iostream>
using std::cout;
using std::size_t;
template <size_t N>
void make3(int(&a)[N]) {
for (size_t i = 0; i < N; ++i) {
a[i] = 3;
}
}
int main() {
int a[3] = { 0, 1, 2 };
make3(a);
int* b = a;
for (size_t i = 0; i < sizeof(a)/sizeof(a[0]); ++i) {
cout << *(b + i) << "\n";
}
}
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);
}
This question already has answers here:
Returning a reference to a local variable in C++
(3 answers)
Closed 8 years ago.
Trying to make a program that sums 5 digit numbers by each digit. For some reason when I attempt to print individual elements of an array (one element at a time running 5 times) I get the correct value of 69134. But when I print them together:
int *addArray(int arr1[], int arr2[]){
int arrSum[5];
int r=0;
for(int i=4; i>=0; i--){
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
return arrSum;
}
int main(){
using namespace std;
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int *arrSum=addArray(data1,data2);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
I end up with the result 60000. Anyone know what is going on?
In addArray you are returning a pointer to a local variable (arrSum), which results in undefined behaviour. You should either pass in the result array from the calling function, or allocate the array dynamically. For example, using the first approach:
void addArray(const int arr1[], const int arr2[], int arrSum[])
{
int r=0;
for(int i=4; i>=0; i--)
{
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
}
int main()
{
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int arrSum[5];
addArray(data1,data2,arrSum);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I have tried to implement a simple function which returns the pointer to first element in array.
#include<iostream>
using namespace std;
int * func(int n)
{
int arr[n];
for (int a = 0; a <n; a++)
{
arr[a]=a;
}
return arr;
}
int main()
{
int n;
cin>>n;
int * arr=func(n);
for (int i = 0; i <n; i++)
{
cout<<*(arr+i)<<endl;
}
}
I have assumed that array occupies contiguous block of memory,then why the output of this program isn't what expected.
if n=10 then output is
0
-1216233191
-1215824576
-1215824576
-1215855028
-1215820256
-1074779464
-1215820256
-1074779464
134514382
int * func(int n)
{
int arr[n]; <<<<<<<<<<<<<<<local variable to this function.
for (int a = 0; a <n; a++)
{
arr[a]=a;
}
return arr;
}
You should not return address of local variables...
This question already has answers here:
non-void function works fine even without executing return
(2 answers)
Closed 10 years ago.
Why does this code print out n-100?
int hello(int n)
{
for(int i = 0; i < n-100; i++)
{
}
}
int main()
{
int h = hello(12);
cout << hello(12) << " " << h << endl;
}
Yet, both of these function return garbage (2665092 and 0 respectively)
int hello1(int n)
{
for(int i = 0; i < 12; i++);
}
int hello2(int n)
{
(n - 100);
}
I compiled this code using g++ in the cygwin environment.
You are simply seeing the result of undefined behaviour.
Always compile with -Wall -Werror to prevent this kind of bug from creeping into your code.