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;
}
}
}
}
Related
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*.
I’m trying to get a pointer to an array that’s in a struct, but doing *(struct->array) gives me an error.
Here’s the code:
#include <iostream>
using namespace std;
struct Numbers {
int highest;
int lowest;
int list[10];
};
void print_pointer_to_first_number(const Numbers* num) {
cout << num.list << endl;
}
int main() {
Numbers numbers;
numbers.highest = 10;
numbers.lowest = 1;
print_pointer_to_first_number(numbers);
return 1;
}
I’m getting an error saying:
error: member reference type 'const Numbers *' is a pointer; did you mean to use '->'?
I am not allowed to change the argument in the function.
You'll want to pass Numbers as reference rather than a pointer (essentially the same, but with nicer syntax):
void print_pointer_to_first_number(const Numbers &num)
Alternatively you can keep it as a pointer, but then you'll need to (1) dereference it properly:
num->list
and (2) pass a pointer when you call it:
print_pointer_to_first_number(&numbers)
I'm trying to understand pointer return types from functions.
The following example produces a type conversion error.
#include <iostream>
using namespace std;
int* abc(int* y)
{
int x=y;
int *z = &x;
x++;
return z;
}
int main()
{
int *a = abc(100);
int b = *a;
cout << a <<endl;
cout << b <<endl;
return 0;
}
The error message is:-
In function 'int* abc(int*)': 6:11: error: invalid conversion from 'int*' to 'int' [-fpermissive]
In function 'int main()': 14:19: error: invalid conversion from 'int' to 'int*' [-fpermissive]
4:6: note: initializing argument 1 of 'int* abc(int*)'
How to resolve the above error and also what is the difference between the following function forms and their appropriate calling syntax,
int* function()
int * function()
int *function()
The argument type in
int* abc(int* y)
is int*. When you call the function,
int *a = abc(100);
you are passing 100, an int. It is not a pointer to an int.
You can fix the problem by using:
Option 1
Change the argument type.
int* abc(int y) { ... }
Option 2
Change the way you call the function.
int x = 100;
int *a = abc(&x);
If you follow this option,
The line
int x=y;
needs to be modified. Type of y is int*, not int. You'll have to change the line to:
int x=*y;
Problem
You are returning the address of a local variable from the function. Dereferencing that address in the calling function is undefined behavior.
When you return an address from a function and the calling function dereferences that address, the address needs to be valid in the calling function. One way to do that is to allocate memory from heap using malloc.
int* abc(int* y)
{
int* x = malloc(sizeof(int));
*x = (*y + 1);
return x;
}
When you do that, you'll have to remember to call free in the calling function.
int x = 100;
int *a = abc(&x);
// Use a
// Deallocate memory
free(a);
The problem is not your return type. Your problem is on this line:
int x=y;
Here y is a pointer and you're trying to assign it to x which is an int.
You're also passing a literal 100 which is an int to the abc function which takes a pointer as an argument.
Finally, there is no difference between the types of the 3 functions you give. Whitespace is insignificant in this context.
Your first two statements in both functions are incorrect. 100 is not a pointer when main calls abc, and blindly assigning y to x won't work because the former is an int and the latter is an int pointer.
This question already has answers here:
If an array name is treated as a pointer, why do I get a compile time error of Lvalue required when incrementing an array?
(3 answers)
Closed 9 years ago.
int main()
{
int a[]={2,3,4,5,6};
int j;
for(j=0;j<5;j++)
{
printf("%d\n",*a);
a++;
}
return;
}
gives Lvalue required error
but
int main()
{
int a[]={2,3,4,5,6};
int *p,j;
p=a;
for(j=0;j<5;j++)
{
printf("%d\n",*p);
p++;
}
return;
}
doesn't.
why????
So I dont understant that even though in a[], a is treated as a pointer so why cant we increment it just like a pointer
Because array name is not a separate memory cell. It is a named memory extent. So it is not clear where to store the incremented value.
Pointers and arrays are not completely interchangeable.
int main ()
{
int var[MAX] = {10, 100, 200};
for (int i = 0; i < MAX; i++)
{
*var = i; // This is a correct syntax
var++; // This is incorrect.
}
return 0;
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value. The reason for this is that var is a constant that points to the beginning of an array and can not be used as l-value.
Because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified
#include <stdlib.h>
int int_sorter( const void *first_arg, const void *second_arg )
{
int first = *(int*)first_arg;
int second = *(int*)second_arg;
if ( first < second )
{
return -1;
}
else if ( first == second )
{
return 0;
}
else
{
return 1;
}
}
In this code, what does this line mean?
int first = *(int*)first_arg;
I thinks it's typecasting. But, from
a pointer to int
to a
pointer to int
little confused here.
Thanks
?
first_arg is declared as a void*, so the code is casting from void* to int*, then it de-references the pointer to get the value pointed from it. That code is equal to this one:
int first = *((int*) first_arg);
and, if it is still not clear:
int *p = (int *) first_arg;
int first = *p;
It is casting a void pointer to a integer pointer and then dereferencing it.
Let's think about it in steps.
void *vptr = first_arg;
int *iptr = (int *)first_arg; // cast void* => int*
int i = *iptr; // dereference int* => int
So, you're specifying the type of data the pointer points to, and then dereferencing it.
int first = *(int*)first_arg;
It's the same as:
int* ptr_to_int = (int*)first_arg;
int first = *ptr_to_int;
That first line does 2 things: it casts the void pointer to an int* and access that memory location to retrieve the value that's there.
There are already many answers to your question, this is more like a comment, something that you will inevitably learn in your quest on mastering C and C++.
Your function is too long. From its name, I predict what you really need is:
int int_sorter( const void *first_arg, const void *second_arg )
{
return *(int*)first_arg - *(int*)second_arg;
}