just a noob trying a programm
i am facing the error and i dont knpw how to resolve it
i wanted the functionto retuen one string that could be used for further use in main
char word_inventory(int ran)
{
char cities[][12]={
"ambala",
"yamunanagar",
"delhi",
"gurgaon",
"jaipur",
"chandigarh",
"pune",
"mumbai",
"dehradun",
"rajpura"
};
return cities[ran];
}
int main()
{ int win=0;
cout<<"welcome to hangman"<<endl;
cout<<"guess the city"<<endl;
randum = rand() % 10 + 0;
strcpy(word,word_inventory(randum)); //here is the error
x=strlen(word);
The immediate error is that cities[ran] is an array of chars, which does not match your function's return type. The array would decay to a pointer to the first element, so you could return char *.
The bigger problem is that the pointer wouldn't be valid, because the lifetime of array into which it points ends at the end of the function call. One solution is to make the array static, so it has permanent lifetime.
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 am a newbie programmer in c++ started my Computer Science degree. I got a problem with my assignment.
You need to make a function char calculate_daily_sale(int []).
You need to define and read an array of integer values of length 10 in the main() function.
Write a function charcalculate_daily_sale (int []) that accepts the array as argument from the main() function. The function will sum the values of array. If the values are greater than or equal to 15,000 the
function return āyā back to the main function, otherwise ānā is returned from the function.
This is the code that I managed to write:
#include <iostream>
using namespace std;
char calculate_daily_sale(int[])
{
int arr[10];
int *ptr[10];
int sum=0;
for(int j=0; j<=9; j++)
{
ptr[j]=&arr[j];
sum=sum+arr[j];
cout<<sum;
}
}
int main()
{
int n,y;
int arr[10];
int *ptr[10];
for(int i=0; i<=9; i++)
{
ptr[i]=&arr[i];
cin>>*ptr[i];
}
if(calculate_daily_sale(int[])>=15000)
{
return y;
}
else
{
return n;
}
return 0;
}
The error that I am getting is:
expected primary expression before 'int'
You need to take a step back and learn the basics of C++ programming.
Some points you should be looking at are:
char calculate_daily_sale(int[])
The function has a return type of 'char' and therefore needs a return statement.
The function parameter is not named and not used. It can be removed entirely.
if(calculate_daily_sale(int[])>=15000)
When calling a function, you need to pass a value, not a type 'int[]'
The return type of is char so it seems odd to be comparing it with 15000.
return y and return n
n and y are uninitialized.
A value returned from main is simply an error code returned to the operating system that runs the programme. It seems unlikely that you want to return these numbers, whatever they are. My reading of the spec is that you need to be returning the characters 'n' and 'y' (for 'yes' and 'no') from your calculate_daily_sale and to main, which is why the return type is char.
Error messages always mention line number. This is the way you can locate the error precisely. Assuming your error is in this line
if(calculate_daily_sale(int[])>=15000)
You probably meant to pass the array arr to calculate_daily_sale:
if(calculate_daily_sale(arr)>=15000)
int main() {
int broccoli,peppers[3]={4,3,2,1} , *zucchini;
zucchini = &peppers[Saute(peppers,1)];
cout<<zucchini<<endl;
}
I know peppers[2] = 2 but just wonder why after Saute function the value of peppers[2] = 3 ? because I think that i only reference the peppers to zucchini and I never declare smtg like this = Saute(&peppers,1)
int Saute(int onions[], int celery) {
celery *= 2;
onions[celery]++;
return celery;
}
In C++, when you pass an array to a function, the array is not copied but passed "as reference" (actually parameter peppers of type int[3] decays to a pointer to the first element of the array, i.e. to an int*, and the type of argument int onions[] is equivalent to int *, too). Hence, when you pass peppers as parameter to function argument onions, and in the function increase a value of the array through onions[celery]++, then you actually increase a value of array pepper.
That's why...
BTW: peppers[3]={4,3,2,1} should be peppers[4]={4,3,2,1}, and you should have got a compiler warning here.
I'm writing an array-based code that is throwing me some confusing errors after failing to compile. I have searched the internet for sample code that I understand more or less but it is helpful for me to identify errors in my own code / thought process.
The task at hand is to create a function that accepts an array of an unknown amount of integers and sums the even numbers in the array. I am told the last entry of the array is -1, but I don't think this information is useful.
Here is my code:
#include <iostream>
using namespace std;
int sumEven(int myArray[])
{
int len = (sizeof(myArray) / sizeof(myArray[0]));
int i = 0;
int count = 0;
while (i < len)
{
if (myArray[i] % 2 == 0)
{
count = count + myArray[i];
}
i++;
}
return count;
}
I attempt to define len as the number of array elements. I think this didn't work since one error refers to this line:
prog.cpp:13:18: error: sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Werror,-Wsizeof-array-argument]
int len = (sizeof(myArray) / sizeof(myArray[0]));
^
prog.cpp:11:17: note: declared here
int sumEven(int myArray[])
^
1 error generated.
I have experience with Matlab, Mathematica, and Python, and so my C++ formatting may be strange. Thanks for taking a look.
The problem is that when passed as arguments to a function, arrays decays to pointers to the first element, so the function
int sumEven(int myArray[]) { ... }
is actually equal to
int sumEven(int *myArray) { ... }
And taking the size of a pointer returns the size of the pointer and not what it points to.
If you need to know the size in the function, you should pass the number of elements as an argument:
int sumEven(int *myArray, size_t len) { ... }
Arrays decay to pointers when you pass them to a function. That means that the information regarding the size of the array is lost.
This means that (sizeof(myArray) / sizeof(myArray[0])) will not do what you want in this context, because here myArray is a pointer.
The canonical solution is to add another parameter representing the array size, and use that instead. This is the approach used in C.
In C++, however, you should probably be using std:: vector, unless you have a specific reason to stick with arrays, which are notoriously error-prone.
int main(int argc, char** argv) {
char a[2][5]={"hell","worl"};
char **p;
p=a; // error here
cout<<*(*(a+1)+1);
cout<<endl;
cout<<(*a)[2];
return 0;
}
error:
C:\Dev-Cpp\main.cpp [Error] initializer-string for array of chars is too long [-fpermissive]
Why would you expect it to work? You declare p as char**,
and you try to assign a char[2][5] to it. The char[2][5]
will convert implicitly to a char (*)[5], but afterwards, you
have a pointer, and no further implicit conversions. (EDIT: except to void*.)
If you think about it, it should be obvious. If you dereference
a char**, you get a char*. And this char* must reside
somewhere in memory, since you have a pointer to it. So where
is it?
If you want to iterate over the outer array in your example:
char (*p)[5] = a;
std::cout << *p[0] << sdt::endl;
std::cout << *p[1] << sdt::endl;
Note that your expression *(*(a+1)+1) also supposes that you
have an array of pointers somewhere.
Or you can use the usual solution when working with C style
strings:
char const* const a[] = { "hell", "worl" };
and
char const* const* p = a;
In this case, you do have an array of pointers, which does
implicitly convert to a pointer to a pointer (the first element
of the array).
(Of course, the only time you'll really want to use C style
strings is with const variables with static lifetimes. In
most other cases, std::string is preferable.)
Other way to access the a[2][5] is,
char **p=(char**)a;
to get a[0]
printf("\n a[0] is [%s]", ((char*)p));
to get a[1]
printf("\n a[1] is [%s]", (((char*)p) + strlen(a[0])+1));
hope this helps.