I am having a run-time error in this program, it has no syntax error but crashes when it is run. i am using dev-c++ 4.9.9.2. I tried to find the error but i couldn't find it. If anyone can help then please find the errors and correct me.
#include<iostream.h>
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
main()
{
DisplayVUID();
char a[20] = "mc123456789";
DisplayReverse(a, 20 );
StoreDiagonal();
system("pause");
}
void DisplayVUID()
{
int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
for(i=0;i<20;i++)
{
cout<<name[i];
}
cout<<endl;
}
void DisplayReverse(char a[], int arraysize)
{
int i;
cout<<"MY VU id in Reverse is ";
for(i=arraysize-1;i>=0;i--)
{
cout<<a[i];
}
cout<<endl;
}
void StoreDiagonal()
{
int a[9][9] ;
int i;
int row, col;
for (i = 0; i<9;i++)
{
for(i=0;i<9;i++)
{
a[row][col] = 0;
}
}
a[1][1] = 1;
a[2][2] = 3;
a[3][3] = 0;
a[4][4] = 2;
a[5][5] = 0;
a[6][6] = 2;
a[7][7] = 3;
a[8][8] = 9;
a[9][9] = 8;
for(i = 0 ; i < 9 ; i ++)
{
for( i = 0 ; i < 9 ; i ++)
{
cout<<a[row][col];
}
}
}
Things don't work this way on Stackoverflow, from next time onward try hard to do things on your own, do your research and then come here.There seemed to be many errors in your program but I tried to remove some bugs and finally, It works on my system. I have also recommended some nice things via comments that you can look in the program:
EDIT: I noticed that some undefined string because of unassigned spaces in the array was printed out in the reverse function but i have corrected it now.
#include<iostream>
#include<stdlib.h>
using namespace std;// use namespace otherwise cout won't work
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
int main()// In C++ always declare a main function like this,its good habit
{
int i=0;
DisplayVUID();
char a[20] = "mc123456789";
while(a[i]!='\0')
i++;// Did this to ensure that cout will print only up to the null character,earlier it was printing some undefined characters along with the data in the array.
DisplayReverse(a, i );
StoreDiagonal();
system("pause");
return 0;//return 0
}
void DisplayVUID()
{
//int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
//for(i=0;i<20;i++)// no need for this loop at least here
//{
cout<<name;
//}
cout<<endl;
}
void DisplayReverse(char a[], int i)
{
cout<<"MY VU id in Reverse is ";
// for(i=arraysize-1;i>=0;i--)
//{
while(i--)
cout<<a[i];//instead of the for loop traversing for the whole arraysize i have made it go up to only the null terminator this way it doesn't print undefined characters.
//}
cout<<endl;
}
void StoreDiagonal()// i don't understand by the way what this function is here for , its not an error though.
{
int a[9][9] ;
int i,j,c=1;
//int row, col;// you didn't initialize row and column and placed it inside the loop
for (i = 0; i<9;i++)
{
for(j=0;j<9;j++)
{
a[i][j] = 0;
if(i==j)
{
a[i][j]=c;//instead of manually assigning do it like this.
c++;
}
}
}
for(i = 0 ; i < 9 ; i ++)
{
for( j = 0 ; j < 9 ; j ++)
{
cout<<a[i][j];// the elements of the array don't display like a table , this is not an error but to make your output readable do it by your self
}
}
}
a[9][9]=8;
remove this line, you will be fine. Array indexing starts from 0 not 1.
Also I would like to point that in your function DisplayVUID() change i<20 to a[i]!='\0' because the values after '\0' will be garbage values.
Related
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;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am just trying to make a simple two player game. First player enters the movie and second player guesses it by using some basics of C++.
movie[] = entered by player 1.
movie_temp[]= a temp array with '_' in it. It updates after every guess by player 2.
MY PROBLEM: Please refer the main function where I called the function movie_check().
This updates the life after every guess. I want the same to happen for my movie_temp array.
When I run this program, only the lives are updated properly, on correct guess the lives are not reduced, but in next turn the array_temp is not updated and the same array is displayed again and again after each gas.
Please help me to create a function which helps to return array and save it in movie_temp (just as I did for life).
IDE: Code::Blocks
Compiler: GCC Compiler
#include<iostream.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
void display_movie(char movie_temp[], int);
void display_life(int);
int win_player2(char movie_temp[]);
int check_life(char movie[], char, int);
void display_movie(char movie_temp[], int len)
{
for(int i=0 ; i<len ; i++)
cout<<movie_temp[i];
}
void display_life(int life)
{
for(int i=0 ; i<=life ; i++)
cout<<"\3";
}
int check_life(char movie[], char ch, int life)
{
int count1=0;
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]==ch)
count1++;
}
if(count1==0)
return --life;
else
return life;
}
int win_player2(char movie_temp[])
{
int count=0;
for(int i=0 ; movie_temp[i]!='\0' ; i++)
{
if(movie_temp[i]=='_')
count++;
}
if(count==0)
return 0;
else
return 1;
}
int main()
{
char movie[100], movie_temp[100], ch;
cout<<"Enter the movie: ";
cin.getline(movie,100);
int len= strlen(movie);
system("cls");
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]=='a' || movie[i]=='e' || movie[i]=='i' || movie[i]=='o' ||
movie[i]=='u' || movie[i]==' ')
movie_temp[i]= movie[i];
else
movie_temp[i]='_';
}
int life=9;
cout<<"\nLives left: ";
display_life(life);
while(life!=0 || win_player2(movie_temp)!=0)
{
cout<<"\n";
display_movie(movie_temp, len);
cout<<"\nEnter your guess: ";
cin>>ch;
life=check_life(movie, ch, life);
cout<<"\n\nLives left: ";
display_life(life);
}
getch();
return 0;
}
enter code here
You make the usual mistake:
movie_temp[i]==movie[i];
should be
movie_temp[i]=movie[i];
Your compiler should have been screaming a warning at you... mine did:
note: use '=' to turn this equality comparison into an assignment
movie_temp[i]==movie[i];
Context (in case you have trouble finding the line):
if(movie[i]==ch)
{
movie_temp[i]==movie[i]; // <<<<<<<<<< this is the line that doesn't copy!
count1++;
}
update just following the warnings that the compiler was giving me, I made a few small changes to your code and now it is working. Mostly, I was heeding the "you are not returning a value!" types of warnings (when you don't explicitly return a value, the compiler will make something up - and most likely you won't find the result useful).
The key is to move the line
return movie_temp;
outside of the for loop in check_movie2:
char* check_movie2(char movie[], char movie_temp[], char ch)
{
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]==ch)
{
movie_temp[i]=movie[i];
}
}
return movie_temp;
}
There are other problems - but this is the one that was biting you the hardest.
Lesson learnt: if your compiler is warning you, LISTEN.
For your entertainment here is the code that I got to run (and that "mostly works". It doesn't currently print out lives correctly and it asks for input after I guessed the title. Also you might consider making the comparison case-insensitive as you are currently sensitive to correct capitalization).
updated added some comments and additional fixes in your code.
#include<iostream>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
using namespace std; // <<<< if you want to use 'cout' instead of 'std::cout' etc, you need this
void display_movie(char movie_temp[], int);
void display_life(int);
int win_player2(char movie_temp[]);
int check_movie(char movie[], char movie_temp[], char, int);
void display_movie(char movie_temp[], int len)
{
for(int i=0 ; i<len ; i++)
cout<<movie_temp[i];
}
void display_life(int life) //displays lives left after each guess
{
for(int i=0 ; i<=life ; i++)
cout<<"+"; // <<<<< I don't know what you are hoping to print with "\3"
// <<<<< Remember that `\` has a special meaning inside a string!
}
int check_movie(char movie[], char movie_temp[], char ch, int life)
{
int count1=0;
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(tolower(movie[i])==tolower(ch)) // <<<<< consider case insensitive match
{
movie_temp[i]=movie[i];
count1++;
}
}
if(count1==0)
{
life--;
return life; //if none of the character is found, life is reduced by 1.
count1=0;
}
return life; // <<<<<< return life here
}
int win_player2(char movie_temp[])
{
int count=0;
for(int i=0 ; movie_temp[i]!='\0' ; i++)
{
if(movie_temp[i]=='_')
count++;
}
return (count==0)?0:1;
}
char* check_movie2(char movie[], char movie_temp[], char ch)
{
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]==ch)
{
movie_temp[i]=movie[i];
}
}
return movie_temp;
}
int main()
{
char movie[100], movie_temp[100], ch;
cout<<"Enter the movie: ";
cin.getline(movie,100);
int len= strlen(movie);
int life=9;
system("cls");
for(int i=0 ; movie[i]!='\0' ; i++)
{
if(movie[i]=='a' || movie[i]=='e' || movie[i]=='i' || movie[i]=='o' ||
movie[i]=='u' || movie[i]==' ')
movie_temp[i]= movie[i];
else
movie_temp[i]='_';
} //initially displays the movie to player 2 and shows only vowels.
cout<<"\nLives left: ";
display_life(life);
while(life!=0 && win_player2(movie_temp)!=0) // <<<<< change || to &&
{
cout<<"\n";
display_movie(movie_temp, len);
cout<<"\nEnter your guess: ";
cin>>ch;
life=check_movie(movie, movie_temp, ch, life);
/*I need to update the life after each round, or else the initially declared
life is passed. */
cout<<"\n\nLives left: ";
display_life(life);
}
return 0;
}
UPDATE - "returning pointers from functions"
To "return an array of values", you need to realize a number of things:
A function can only "return" a simple value (int, float, pointer, ...)
If you create an array inside a function, you need to make sure the
space allocated remains valid after you return
You can pass a pointer to a function, and let the function update values in the space pointer to
Simple example (C) on different approaches (including one that doesn't work):
does not work:
int * foo() {
int A[]={1,2,3,4,5};
return A;
}
int main(void) {
int *X;
X = foo();
printf("%d", X[0]); // UNDEFINED BEHAVIOR
return 0;
}
This doesn't work because the array A stops existing ('goes out of scope') when the function returns. Accessing memory pointed to by X results in undefined behavior.
works, but only use in single threaded environment:
int * foo() {
static int A[]={1,2,3,4,5};
return A;
}
this works because the array is static so it is allocated differently and "survives" after the function returns. Not recommended.
pass a pointer and size of array: (example increments an array)
void foo(int *a, int n) {
int ii;
for(ii=0;ii<n;ii++) a[ii]++;
}
int main(void) {
int n=5;
int X[5] = {1,2,3,4,5};
foo(X, 5); // values in X will be incremented in-place
Returning value in another array:
void foo(int *A, int *B, int n) {
int ii;
for(ii=0; ii<n; ii++) B[ii] = 2 * A[ii];
}
int main(void) {
int a[5] = {1,2,3,4,5};
int b[5];
foo(a, b, 5);
printf("%d\n", b[0]); // returns a value of 2
return 0;
}
This is starting to be more sensible. Finally, if you want an array to be created by the function, you can do
int *foo(int n) {
int *X, ii;
X = malloc(n * sizeof *X);
for(ii = 0; ii < n; ii++) X[ii] = 2 * ii;
return X;
}
int main(void) {
int *a;
a = foo(5);
printf("%d", a[4]); // will print 8
free(a); // remember to do this after you finished using the array or you get a memory leak!
return 0;
}
I hope these additional examples and their explanation improves your understanding of these techniques a little bit.
This is my first time here. I really hope anyone can help me out there. So this is my problem. I keep getting run time error #2 something about a corrupt "arr". But the program runs fine until the end. I can't figure it out.
This is my code:
#include <iostream>
using namespace std;
void main(){
int arr1[3];
int temp;
//INPUT NUMBERS
for (int i=0; i<5;i++)
{
cin>>arr1[i];
}
cout<<endl;
//SORT
for(int c=0;c<5;c++)
{
for (int k=0;k<5;k++)
{
if(arr1[c]<arr1[k])
{
temp=arr1[k];
arr1[k]=arr1[c];
arr1[c]=temp;
}
}
}
for (int m=0; m<5; m++)
{
cout<<arr1[m]<<endl;
}
}
Try this out:
#include <iostream>
using namespace std;
int main()
{
int arr1[5];
int temp;
//INPUT NUMBERS
for (int i = 0; i < 5; i++) {
cin >> arr1[i];
}
cout << endl;
//SORT
for (int c = 0; c < 5; c++) {
for (int k = 0; k < 5; k++) {
if (arr1[c] < arr1[k]) {
temp = arr1[k];
arr1[k] = arr1[c];
arr1[c] = temp;
}
}
}
for (int m = 0; m < 5; m++) {
cout << arr1[m] << endl;
}
}
It compiles properly without any errors. The mistake you had made is in declaring the size of the array. If you want to store 5 in puts, you need to declare an array of size 5. Your code might work, but a good compiler will always give out an error.
The reason being that when you declare an array, you actually create a pointer to the first element of the array. And then, some memory regions are kept for this array, depending on the size. If you try to access an element that is outside these memory regions, you may encounter a garbage value.
Here's your code in ideone.
I would like to have an array int candidates[9][] where the first dimension is known (9) and the second, depends on the execution.
I found that a method to allocate the array was the following:
int *candidates[9]; /* first allocation at declaration */
for(int i=0;i<9;i++) candidates[i] = new int[6]; /* allocation at execution */
but when I use it like that, and I try to access to candidates[i][j], it doesn't work. I initialize candidate[i] with a function fun() that return and int[] of the right size, but the content of candidate[i][j] is wrong.
candidates[0] = fun();
I don't understand where I am wrong... Thank you for your help :-)
Try int *candidates[9] instead of int candidates[9][] and it should work.
Why dont you try vector template class from STL...code is more neater and comprehensive...
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arrayOfVecs[9];
//use each array to put as many elements you want, each one different
arrayOfVecs[0].push_back(1);
arrayOfVecs[1].push_back(100);
.
.
arrayOfVecs[1].push_back(22);
arrayOfVecs[0].pop_back();
arrayOfVecs[8].push_back(45);
cout<<arrayOfVecs[1][0]<<endl;//prints 100
return 0;
}
WITH ARRAY OF POINTERS
int main()
{
int* arrayOfPtrs[9];
for(int index = 0;index<9;index++)
{
int sizeOfArray = //determine the size of each array
arrayOfPtrs[index] = new int[sizeOfArray];
//initialize all to zero if you want or you can skip this loop
for(int k=0;k<sizeOfArray;k++)
arrayOfPtrs[index][k] = 0;
}
for(int index = 0;index<9;index++)
{
for(int k=0;k<6;k++)
cout<<arrayOfPtrs[index][k]<<endl;
}
return 0;
}
Try int **candidates=0; followed by candidates = new int *[9] ;.
Code:
#include <iostream>
using namespace std;
int main(void)
{
int **candidates=0;//[9]; /* first allocation at declaration */
candidates = new int *[9] ;
for(int i=0;i<9;i++) candidates[i] = new int ; /* allocation at execution */
for( i = 0 ; i < 9 ; i++ )
{
for( int j = 0 ; j < 9 ; j++ )
{
candidates[i][j]=i*j;
cout<<candidates[i][j]<<" ";
}
cout<<"\n";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
I am writing a Little Man computer simulation and i want to overload the Indexing operator []. I have create a class called LMC and have done the following:
#include <iostream>
using namespace std;
class LMC
{
public:
LMC();
void display();
int& operator[](int index);
~LMC();
private:
int **array;
};
LMC::LMC()
{
array = new int*[100];
for(int i = 0; i < 100; i++)
{
array[i] = new int[3];
}
return array;
}
void LMC::display()
{
for(int i = 0; i < 100;i++)
{
for(int j = 0; j <3;j++)
{
array[i][j] = 0;
array[i][2] = i;
cout << array[i][j]<<" ";
}
cout << endl;
}
}
int& LMC::operator[](int index)
{
return array[index][2];
}
LMC::~LMC()
{
for(int i =0; i < 100 ; i++)
{
delete [] array[i];
}
delete [] array;
array = NULL;
}
int main()
{
LMC littleman;
while(true)
{
int mailbox;
int function;
cout << "What is Mailbox number?" << endl;
cin >> Mailbox;
cout << "What is the function you want to use?" <<endl;
cin >> finction;
//the function is numbers eg 444 and 698;
littleman.display();
littleman[Mailbox] = function;
}
return 0;
}
I can run the program with no error. When i state that mailbox = 0 and function = 123 the is no problem.
This is displayed:
0 0 0
1 0 0
2 0 0
3 0 0
//continuing to 99
This display is wrong. The following must be displayed:
0 0 123
1 0 0
2 0 0
//continuing to 99
Do i have a logical error or am i overriding the array to display the original and how can i fix it?
Your code has a number of errors which will not let it compile namely:
in the LMC() constructor, you have return array;. Constructors never return anything (they don't even have the return type), so you can not use return in them.
after void LMC::display(), you have a ;, which is an error, because this is not a definition, but implementation. You should omit it and just leave void LMC::display() { <...> }
void LMC::display() is missing the closing } in the end, right before the operator[].
in main() you have typos in Mailbox (capital M in one case, and normal m in another. In C+++ Mailbox and mailbox are different variables) and finction instead of function.
As for your problem, you are rewriting the values of the aray in display() function:
array[i][j] = 0;
array[i][2] = i;
That's why you don't see any results.
These lines
array[i][j] = 0;
array[i][2] = i;
in LMC::display() destroy the contents of the array you're trying to display.
Furthermore, there's an extra semicolon at the end of void LMC::display();, so your code is not supposed to compile.