Passing a pointer to an int array, as an argument C++ - c++

I know even if i pass an array by typing arrayname as argument (ex: getArrayInput(arrayexample); ), it will copy only the adress value of first element not entire array,still i wonder why these code gives error. I know this not the way how it should implemented but i want to understand this error.
main.cpp|13|error: cannot convert 'int*' to 'int**' for argument '1' to 'void getArrayInput(int**)'|
#include <iostream>
using namespace std;
void getArrayInput(int * []);
int main()
{
cout<<"Enter scores on by one.." << endl;
cout<<"To terminate input enter -1"<<endl;
int listof[10]={};
int *ptScores =listof;
getArrayInput(ptScores);
return 0;
}
void getArrayInput(int * []){
for(int i=0;i<10;i++){
cin>>*(pt+i);
if(*(pt+i))=-1){
break;
}
else{
cout<<"Enter next.."<<endl;
}
}
}

It is because
int *
and
int[]
are both of type
int *
therefore, you are here asking for a
int **.
try replacing
void getArrayInput(int * []) by void getArrayInput(int *)

In C, arrays decay in to pointers. In some cases, they are interchangable.
ptScores is of type int* (pointer to int).
getArrayInput expects an int*[] (array of pointers to int).
int*[] decays in to int** (pointer to pointer to int).
The error says you're giving an int* (ptScores) to something that expects an int** (getArrayInput).
How do you fix this?
Take an int*.
void getArrayInput(int* pt){
for(int i=0;i<10;i++){
cin>>pt[i];
if(pt[i]=-1){
break;
}
else{
cout<<"Enter next.."<<endl;
}
}
}

Related

I am getting this strange compilation error in C++

I was doing the Coin change problem, I am trying to do it using Dynamic Programming. But I am getting this compilation which I don't quite understand. Someone told me that I have to assign the 'dp' array dynamically, but he was not sure why. PLease explain this concept .
#include<bits/stdc++.h>
using namespace std;
int solve(int *d, int size, int n , int ** dp){
if(n==0)
return 1;
if(n<0)
return 0;
if(size == 0)
return 0;
if(dp[n][size]>-1)
return dp[n][size];
int x = solve(d,size,n-d[0],dp);
int y = solve(d+1, size - 1, n, dp );
dp[n][size] = x+y;
return x+y;
}
int countWaysToMakeChange(int denominations[], int numDenominations, int value){
int dp[value+1][numDenominations+1];
memset(dp, -1, sizeof dp);
return solve(denominations, numDenominations, value, dp );
}
Error :
Compilation Failed
In file included from Runner.cpp:3:0:
Solution.h: In function 'int countWaysToMakeChange(int*, int, int)':
Solution.h:28:60: error: cannot convert 'int (*)[(numDenominations + 1)]' to 'int**' for argument '4' to 'int solve(int*, int, int, int**)'
return solve(denominations, numDenominations, value, dp);
^
Here is my Main file code:
#include<iostream>
using namespace std;
#include "Solution.h"
int main(){
int numDenominations;
cin >> numDenominations;
int* denominations = new int[numDenominations];
for(int i = 0; i < numDenominations; i++){
cin >> denominations[i];
}
int value;
cin >> value;
cout << countWaysToMakeChange(denominations, numDenominations, value);
}
There are two problems in the code.
First, in the function int countWaysToMakeChange(int denominations[], int numDenominations, int value)
int dp[value+1][numDenominations+1];
is illegal. Array bounds must be compile-time constants. Some compilers allow this sort of things as an extension (and it's legal in C), but it is not valid C++.
Second, the type of dp is "array of array of int". It is not a "pointer to pointer to int", and the compiler is complaining that it can't make that conversion when the code tries to pass dp as the fourth argument to solve.
Arrays are confusing. In most contexts, the name of an array decays into a pointer to its first element. That's why you can write code like this:
void f(int*);
void g() {
int array[20];
f(array);
}
Since dp is an array, its name decays into a pointer to its first element. But this is where it's easy to get lost: as I said earlier, the type of dp is "array of array of int"; when its name decays, the resulting type is "pointer to array of int".
If you want to pass dp to solve, solve has to take the same type: "pointer to array of int". But since you don't know the size of that array when you write solve you can't write that type in the argument list.
That's one reason why multi-dimensional arrays are often represented as one-dimensional arrays, with code to convert the two dimensions into one. The offset is x * width + y, or some minor variant on that. When you do that, your two-dimensional array becomes a one-dimensional array, and its name decays into a pointer to its first element, so you can pass it to a function that expects int*.

C++ how to pass string array in function and assign to a variable?

I got this error while coding a simple function. This is my function specification.
string studentName;
string courseTaken[3];
void setStudent(string, string[]);
void Student::setStudent(string n, string a[])
{
studentName= n;
courseTaken = a;
}
This is the error I have gotten:
incompatible types in assignment of string* to string [3] on this line courseTaken = a;
In my code, I never declared any pointer or char.
I don't quite understand what is going wrong here.
You can not assign array of strings string a[] to array courseTaken using = operator. The expression string a[] is equivalent to std::string*. That is why you get the compiler error.
This may be what you wanted:
#include <iostream>
using namespace std;
class Student
{
public:
string studentName;
string courseTaken[3];
void setStudent(string n, string a[]);
};
void setStudent(string n, string a[]);
void Student::setStudent(string n, string a[])
{
studentName = n;
for(int i=0; i < sizeof(courseTaken)/sizeof(courseTaken[0]); i++)
courseTaken[i] = a[i];
}
int main()
{
Student student;
string courses[3] = {"Cobol","C++","Fortran"};
student.setStudent("Eva", courses);
for (int i = 0; i < 3; i++){
cout << student.courseTaken[i] << endl;
}
return 0;
}
Output:
Cobol
C++
Fortran
It seems you don't understand array decay mechanism of C-format arrays.
For many context, an array name will be explained as a pointer to the first element of the array. And this pointer is a prvalue which just like this pointer, you can NOT assign to it.
the "modern Cpp way"(C++11) is to use std::array, which overloaded the =operator and stores the size of the array so that it won't be decayed while passing to a function.
The second way is to pass the reference, with a template you can ensure the array's size, then use std::memcpy. And you can add a parameter stores the array's size, and then you can use memcpy too.
I hope you use the first way, don't forget -std=c++11
This is because you are passing an array to a variable that's why this error occurs. To solve this problem you may use pointer in argument to solve this problem. Change your function to this.
void Student::setStudent(string n, string* a)
{
studentName= n;
courseTaken = a;
}

Passing multidimensional arrays gives and error

I am trying to pass a multidimensional array to a function. When I try to compile I an getting an error saying
[Error] cannot convert 'int (*)[3]' to 'int (*)[2]' for argument '1' to 'void reve(int (*)[2], int)'
What is the problem ? What am I doing wrong? Following is the code I wrote.
#include <iostream>
using namespace std;
const int rows=2;
const int cols=2;
const int n = 3;
void reve(int arr[rows][cols],int n){
int br[3][3],i,j,k,l;
for(i=n-1,k=0;i>=0,k<n;i--,k++){
cout<<endl;
for(j=n-1,l=0;j>=0,l<n;j--,l++)
br[k][l]=arr[i][j];
}
for(i=0;i<n;i++){
for(j=0;j<n;j++)
arr[i][j]=br[i][j];
}
}
int main() {
int i,j,k,l,ar[3][3],br[3][3];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>ar[i][j];
int n=3;
reve(ar,n);
for(i=0;i<3;i++){
cout<<endl;
for(j=0;j<3;j++)
cout<<ar[i][j];
}
return 0;
}
When you use a 2-d array in a function call, it decays into a pointer type. However, all dimensions but the first one must match exactly.
If the argument type of a function is int (*arg)[2], then, you can't use a variable that is declared as int var[3][3] to call the function. var decays to a pointer whose type is int (*)[3].
It is confusing at first because it seems to work in case of 1-d arrays.
void foo(int arg[10])
{
}
int var[2];
foo(var); // OK
That's because the compiler ignores the size of the first dimension of the array. The above definition of foo is same as:
void foo(int arg[])
{
}
and
void foo(int* arg)
{
}
However, for a multidimensional array, the size of all but the fist dimension must match exactly. Otherwise, they are different types.
The reve() function expects an array of [2][2] but you're passing a [3][3] array.
The ar array in main() is declared as int ar[3][3] while it should have been int ar[rows][cols]
You have reserved 2 blocks in memory. And in your loop, you are taking it from 2 to 0 that makes it 3. Do the following changes.
const int n= 2;
And it should work for your program.

Structures and functions(passing by reference)

Please guide me on this code, I want to store list of 5 data using array and function, this is a piece of code of mine, but this is giving me an error ("33"):
Cannot convert `ABC (*)[5]' to `ABC*' for argument `1' to `void pass(ABC*)'
Code:
#include <iostream>
using namespace std;
struct ABC{
char name[20];
int phone;
char address[20];
};
void pass(ABC *abc){
for(int i=0; i<5;i++){
cout<<"Enter name"<<endl;
cin>>abc[i].name;
cout<<"Enter phone"<<endl;
cin>>abc[i].phone;
cout<<"Enter address"<<endl;
cin>>abc[i].address;
}
}
int main()
{
ABC abc[5];
pass(&abc);
system("PAUSE");
return EXIT_SUCCESS;
}
You can use pass(&abc[0]); or pass(abc); to get a pointer to the first element in the array. Otherwise if you use &abc alone you get a pointer to a whole array[5] not the elements inside the array.
Arrays are not pointers. But they can decay to pointers when you are doing function calls.
So you can pass your array like this:
pass(abc);

C++, error invalid conversion from `int*' to `int'

I have the following C++ code:
#include <iostream>
using namespace std;
int main(){
}
int findH(int positionH[]){
return positionH; //error happens here.
}
The compiler throws an error:
invalid conversion from `int*' to `int'
What does this error mean?
positionH[] is an array, and its return type is int.
The compiler will not let you do that. Either make the parameter an int:
int findH(int positionH){
return positionH;
}
Or make the return type a pointer to an int:
int* findH(int positionH[]){
return positionH;
}
Or convert the array to an integer before return:
int findH(int positionH[]){
return positionH[0];
}
This line is invalid C++ (and invalid C too, which your code appears to be written in):
int bla[2] = findH(field, positionH);
bla is an array of 2 elements and cannot be initialised that way. findH returns int.
This error is coming while you are trying to do:
int *p =10;
that means you are assigning int value to pointertoint *p .
But pointer is storing address that means *p is taking 10 as address.
So
just do:
int i=10;
int *p=&i;
or
p=&i;
it will not give any error.
The error was caused because you returned a pointer and the compiler is expecting a int.
There is a very BIG difference between int * and int.
Also why are you returning positionH, arrays are passed by reference, there is no need to return it.
Better code would be
void option1(char** field, int[])
{
int findH(char **, int[]);
int positionH[2];
findH(field, positionH);
//positionH passed by reference, no need to return it
}
void findH(char **field, int positionH[])
{
for(int n = 0;n < 14 ; n++)
{
for(int m = 0; m < 14; m++)
{
if(field[m][n] == 'H')
{
positionH[0] = n;
positionH[1] = m;
}
}
}
}