I'm a beginner in c++ and I'm getting two errors in my code and I don't know how to fix them...
the first one
illegal indirection
and the second one is
'=' left operand must be a I-value. (in the line: ((ArrayPtr +i)+j)=rand()%55+1 )
Does anyone have an idea how to fix them? That's my code:
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 6;
void FillingRandomly(int (*)[AS]);
void printing(int (*)[AS]);
int c;
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
FillingRandomly(Array);
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
printing(Array);
system("PAUSE");
return 0;
}
void FillingRandomly(int *ArrayPtr)
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS;j++)
{
*(*(ArrayPtr +i)+j)=rand()%55+1;
}
}
}
void printing(int *Array)
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS*AS;j++)
{
int counter = 0;
cout<<((Array[i] +j))<<setw(5);
if ((Array[i] +j)%AS == 0)
cout << endl << endl;
}
}
}
void forsorting(int *Brray, int funny)
{
int dice = 0;
int super = 0;
int space=0;
//Sorting Array[][] which is treated like Array[]
{
for (int pass = 0; pass < AS - 1; pass++) {
for (int k = 0; k < AS - 1; k++) {
int temp;
if(*(Brray+k)==*(Brray+k+1))
{
temp=*(Brray+k);
*(Brray+k)=*(Brray+k+1);
*(Brray+k+1)=temp;
}
}
}
}
}
By
*(*(ArrayPtr +i)+j)=rand()%55+1;
it seems you want
ArrayPtr[i][j] = (rand() % 55) + 1;
You can try something along the line of
int const offset = AS * i + j;
int const elem = (rand() % 55) + 1;
*(ArrayPtr + offset) = elem;
Your function signature is:
void FillingRandomly(int *ArrayPtr)
where you are telling to compiler that you are passing a simple pointer, but in the line:
*(*(ArrayPtr +i)+j)=rand()%55+1;
you are doing a double derreference, which is illegal and causing the compiler to complain
COMPLEMENT
I was seeing the comments in the other answer and, as what I need to write is bigger than the reserved commentary space, I decided to complement my own answer.
You defined Array as:
int Array[AS][AS];
Indeed, what you are doing is a promise to compiler that you will use Array as defined, but the compiler doesn't believe in you too much, so that any time you use Array the compiler will make sure that it is being used as declared.
The problem arises when you declare your FillingRandomly function. Here you are broking your promise and are trying to use Array by declaring a differente type. Note how you declare your function:
void FillingRandomly(int *ArrayPtr)
Due the fact that c++ supports function overloading, the compiler doesn't warn you until it initiate the linking phase, when it is unable to find a function whose signature is:
void FillingRandomly(int ArrayPtr[][AS])
note that both are different.
Once you are a beginner, the best way to keep your programs correctly is to keep your promise immutable. Bellow I show you a piece of your own code, correcting those issues for FillingRandomly function (you have to correct it for the others functions too):
const int AS = 6;
void FillingRandomly(int [][AS]); // Note that I've changed your prototype here
....
void FillingRandomly(int ArrayPtr[][AS]) // Keep your function signature the same as your prototype signature
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS;j++)
{
ArrayPtr[i][j]=rand()%55+1; // Note how ArrayPtr is being used exactly as your promised early
}
}
}
Related
I have passed an array of size 10 to a funtion to sort the array reversely, but it's going wrong after rightly sorting first five elements of the array.
I want to sort the array 'std' reversely here,
# include <iostream>
using namespace std;
int reverse(int a[]); //funtion prototype
int main()
{
int std[10] = {0,1,2,3,4,5,6,7,8,9};
reverse(std);
}
int reverse(int a[]) //funtion defination
{
int index = 0;
for (int i = 9; i >= 0; i--)
{
a[index] = a[i]; //swaping values of the array
cout << a[index] << " ";
index++;
}
}
There's basically three things wrong with your code.
You aren't swapping anything
You have to swap the first half of the array with the second half, not swap the whole array. If you do that then everything gets swapped twice, so that nothing changes
You should print the reversed array after you have finished the reverse, not while you are doing the reverse.
Here's some code that fixes all these problems
# include <iostream>
# include <utility>
void reverse(int a[]);
int main()
{
int std[10] = {0,1,2,3,4,5,6,7,8,9};
reverse(std);
// print the array after reversing it
for (int i = 0; i < 10; ++i)
std::cout << std[i] << ' ';
std::cout << '\n';
}
void reverse(int a[])
{
for (int i = 0; i < 5; ++i) // swap the first half of the array with the second half
{
std::swap(a[i], a[9 - i]); // real swap
}
}
Yes you can.
I usually don't use "C" style arrays anymore (they can still be useful, but the don't behave like objects). When passing "C" style arrays to functions you kind of always have to manuall pass the size of the array as well (or make assumptions). Those can lead to bugs. (not to mention pointer decay)
Here is an example :
#include <array>
#include <iostream>
// using namespace std; NO unlearn trhis
template<std::size_t N>
void reverse(std::array<int, N>& values)
{
int index = 0;
// you only should run until the middle of the array (size/2)
// or you start swapping back values.
for (int i = values.size() / 2; i >= 0; i--, index++)
{
// for swapping objects/values C++ has std::swap
// using functions like this shows WHAT you are doing by giving it a name
std::swap(values[index], values[i]);
}
}
int main()
{
std::array<int,10> values{ 0,1,2,3,4,5,6,7,8,9 };
reverse(values);
for (const int value : values)
{
std::cout << value << " ";
}
return 0;
}
really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code
#include <iostream>
#include <array>
#include <vector>
using namespace std;
// Selection Sort :
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
return m;
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void selectionSort(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); ++i)
{
int min = findMin(arr, i);
swap(arr[i], arr[min]); // Assume a correct swap function
}
}
}
void print(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << "";
cout << endl;
}
}
}
int main()
{
vector<int> sort;
sort.push_back(2);
sort.push_back(1);
sort.push_back(7);
sort.push_back(4);
sort.push_back(5);
sort.push_back(3);
print(sort);
cout << "this was unsorted array";
cout << endl;
cout << findMin(sort, 0);
cout << "this was minimum";
cout << endl;
selectionSort(sort);
print(sort);
}
I am getting the following results:
comparison_sort.cpp:20:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
}
^
1 warning generated.
2
1
7
4
5
3
this was unsorted array
1
this was minimum
1
2
4
5
3
0
My question is: What is causing this control path error? Why is the "7" here being replaced with a "0"?
Thanks in advance! Sorry for the noob question.
I have reviewed all my current functions and nothing seems to explain why the 7 is replaced with a 0. I have tried multiple integers and it looks like the maximum number is always replaced.
The warning is very real, and it alludes to the problem that's breaking your sort as well.
You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element.
And of course, if a is the last index of the array, then the loop will never execute, and you will never explicitly return a value. This is the "control path" which does not return a value.
It's quite clear that you've accidentally put return m; in the wrong place, and even though you have good code indentation, some inexplicable force is preventing you from seeing this. To fix both the warning and the sorting issue, move return m; outside the loop:
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
}
return m;
}
I am trying to use pointers whenever possible in the following code and am having difficulty figuring out how, exactly, to institute the pointers and how to return a pointer value at the end of my first function. I have done some research on the subject but none of the methods I found have been helpful so far, so I was hoping you may have some specialized tips.
Note: I am a beginner.
#include <iostream>
using namespace std;
int mode(int *pies[], int size) {
int count = 1;
int max = 0;
int *mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return *mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
Here is an attempt to answer.
In your main(), you call the mode() function with mode(survey, n) while int survey[n]; is an array of int, so you may use int mode(int *pies, int size) instead of int mode(int *pies[], int size) (as the array int survey[n] can be implicitly converted into pointer).
However, you need to modify two more things in your function:
int *mode=pies[0]; is wrong as pies[0] is the first element of an array of int, thus is an int, while int* mode is a pointer on an int which is incompatible. mode should be an int to receive pies[0]. The correct code is then int mode = pies[0].
Your function signature is int mode(int *pies, int size), thus, again, you should return an int. You should then just return mode;
These are only hints on how to make the code compile.
Your next step is to formalize what you would like it to do and then modify the code accordingly
NB: The correct practice is to think about what you would like to achieve first and then code afterwards (but let us say that this is for the sake of helping each other)
To get started using pointers, you may look at some simple tutorials at first:
http://www.cplusplus.com/doc/tutorial/arrays/
https://www.programiz.com/c-programming/c-pointers
https://www.programiz.com/c-programming/c-pointers-arrays
https://www.geeksforgeeks.org/pointer-array-array-pointer/
https://www.geeksforgeeks.org/how-to-return-a-pointer-from-a-function-in-c/
https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm
Here is the modified code with the stated modifications above (it compiles):
#include <iostream>
using namespace std;
int mode(int *pies, int size) {
int count = 1;
int max = 0;
int mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
my lecturer created this function in a live code clinic and I am trying to copy it out then re-write it multiple times until I have learnt and understood the code.
Currently I'm unsure where I need to define the "findgreatest" function for the program to run. I was under the impression that you had to define functions within the main(). However, there are likely more errors I'm not seeing. Anyways, some help to get this code running and explained in more detail would be greatly appreciated.
Thanks
Alex
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, const char * argv[]) {
const unsigned int size = 15; // creates a const int for array
int a_sig [size]; // assigns int to array size
for(int i=0; i<size; i++) {
a_sig[i] = rand() % 100;
cout << *(a_sig+i) << endl;
}
int findgreatest (int size, int a_sig) { //"F deceleration not allowed"
int max = -1;
for (int i = 0; i < size; i++) {
if (*(a_sig+i) > max){
max = *(a_sig+i);
}
}
return max;
};
int maximum;
maximum = findgreatest(size, a_sig); //"undeclared identifier"
return 0;
};
Currently I'm unsure where I need to define the "findgreatest" function for the program to run. I was under the impression that you had to define functions within the main().
Actually, you cannot define named functions in main. You can see this in the error declaration not allowed.
Functions must be declared before use. During compilation, the compiler will note where functions are defined. When the compiler sees one of these functions called, it knows what instructions to put since it is aware that these functions exist. But if a function isn't declared (and defined), then the compiler cannot interpret function calls.
You should either define your function before main, or declare your function before main and define it after main.
Option: Defining function before main
If you want to define the function before main, your code might look like
#include <iostream>
#include <ctime>
#include <cstdlib> // rand is defined here
using namespace std;
// Defines findgreatest
// findgreatest is now available for use later in program
int findgreatest (int size, int a_sig[]) // I added a `[]` in this signature
{
int max = -1;
for (int i = 0; i < size; i++) {
if (*(a_sig+i) > max){
max = *(a_sig+i);
}
}
return max;
}
int main(int argc, const char * argv[]) {
const unsigned int size = 15; // creates a const int for array
int a_sig [size]; // assigns int to array size
for(int i=0; i<size; i++) {
a_sig[i] = rand() % 100;
cout << *(a_sig+i) << endl;
}
int maximum;
maximum = findgreatest(size, a_sig);
// You probably want to do something with the maximum?
cout << "\nMaximum is " << maximum << endl;
return 0;
} // (I removed an unnecessary semicolon here)
Option: Declaring function before main, define after
Alternately, you can declare the function (i.e. give a description of its name and signature) and define it later. You can do this with
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
// declares findgreatest
// The compiler knows that this function is defined somewhere and can make
// references to it. If the definition isn't also provided during compilation,
// an error is raised.
int findgreatest (int size, int a_sig[]);
int main(int argc, const char * argv[]) {
const unsigned int size = 15; // creates a const int for array
int a_sig [size]; // assigns int to array size
for(int i=0; i<size; i++) {
a_sig[i] = rand() % 100;
cout << *(a_sig+i) << endl;
}
int maximum;
maximum = findgreatest(size, a_sig);
// You probably want to do something with the maximum?
cout << "\nMaximum is " << maximum << endl;
return 0;
}
// Definition
int findgreatest (int size, int a_sig[])
{
int max = -1;
for (int i = 0; i < size; i++) {
if (*(a_sig+i) > max){
max = *(a_sig+i);
}
}
return max;
}
Additional notes
To use rand(), you need to #include <cstdlib>.
You compute maximum but don't do anything with it. I added a statement outputting this to the terminal at the end of main.
I removed a semicolon after main(){}.
Your function signature findgreatest(int size, int a_sig) isn't quite right. The second argument is an array, not an int. There are a few different ways to denote this, but I changed it to findgreatest(int size, int a_sig[]) to indicate to the compiler that it should be expecting an array.
When you learn more about arrays, you'll know a bit more about that. And you'll probably revisit the expressions *(a_sig + i), which are a bit odd.
(Please keep in mind I've only recently delved into C++ functions.)
Let's say that you want a function that will count from 1 to a specific number.
#include <iostream>
int countTo(int num);
int countTo(int num) {
for (int i = 1; i <= num; i++) {
std::cout << i << "\n";
}
return num;
}
int main() {
int num;
std::cout << "Enter a number to which the program will count: ";
std::cin >> num;
countTo(num);
return 0;
}
I've put the same code into the compiler, just without the parameters on the function declaration, like so:
int countTo();
int countTo(int num) {
for (int i = 1; i <= num; i++) {
std::cout << i << "\n";
}
return num;
}
And it worked just as well. Do I need to include parameters when declaring int countTo(int num)? Or for any function?
std::cout << "Thanks!!";
There are two different things going on when you write this:
int countTo(int num) {
for (int i = 1; i <= num; i++) {
std::cout<<i<<"\n";
}
return num;
}
You are declaring a function called countTo that takes an int and returns an int, and you are also defining the function.
When you have the line above it saying
int countTo(int num);
you are declaring the same function, but not defining it.
When you changed that line to
int countTo();
you declared a different function (an overload) that takes no parameters. It doesn't matter that you didn't define that function, because no one ever tried to call it.