My program is this:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char choice;
int o,i,marks[i],ttlcredit=0;
double ttlGPA=0,finalGPA=0,credit[7][2],clsavg;
cout<<"Please enter what you want to calculate"<<endl;
cout<<"A for calculating Class Average GPA"<<endl;
cout<<"B for calculating a Specific GPA"<<endl;
cout<<"Your choice is? ";
cin>>choice;
cout<<endl;
if (choice == 'A'||choice == 'a')
{
cout<<"=========================================="<<endl;
cout<<" Class Average GPA"<<endl;
cout<<"=========================================="<<endl<<endl;
cout<<"Please enter the number of students in the class: ";
cin>>number;
for(i=0;i<number;i++)
{
cout<<"\nEnter student #"<<i+1<<"'s marks: ";
cin>>marks[i];
ttlGPA=ttlGPA+marks[i];
}
clsavg=ttlGPA/number;
cout<<"\nThe Average is: "<<clsavg<<endl;
}
else
{
}
}
It is half completed. When I build and run on CodeBlocks, an error instantly appeared:
I tried finding the source of error and I think that it is caused by the following in the code:
int o,i,marks[i],ttlcredit=0;
What makes me think so is because when I remove the [i] from marks[i], I will be not receive that error.
I think is stack overflow because I use Microsoft Visual Studio to help me debug and this is the error they gave me:
Unhandled exception at 0x0041419e in Project (1).exe: 0xC00000FD: Stack overflow.
My question is...
Is that the main cause of problem?
How do I resolve this issue?
You have to initialize the marks array with a positive length.
Get the number of students first, THEN create the array using that number.
Also, you need to declare the variable number.
As the other answers stated correctly, the problem is that int i is used uninitialized. However, the proposed fix
// initialze i
int marks[i];
is not standard C++, but only available through a compiler extension. In C++, the length of a built-in array must be a compile time constant. The better solution would be using std::vector:
// initialize i (better make it std::size_t instead of int)
std::vector<int> marks (i);
This will create a variable length array in a safe and standard conforming way.
First thing to say is that you simply shouldn't use arrays. They just are too weird in C and C++, and we have superior alternatives in modern C++.
Anyway, whether you use arrays or vectors, there are some important issues. Before discussing marks[i], it's simpler to look at credit[7][2] in this code.
int o,i,marks[i],ttlcredit=0;
double ttlGPA=0,finalGPA=0,credit[7][2],clsavg;
The dimensions are explicit in this declaration of credit. It's seven-times-two. Simple enough. You can read and write to credit[0][0] and credit[6][1] and many other values. But if you go outside the range, e.g. try to use credit[7][0], your program will compile and will probably appear correct for a while, but it could behave very badly and it is undefined how it will behave. It could decide to delete all the files on your computer, it is (seriously) entitled to do anything random and crazy. This is Undefined Behaviour.
Anyway, the really weird line is the declaration of marks.
int marks[i];
This definitely doesn't do what you think it does. It doesn't create an array that can be "indexed with arbitrary i". No, it allocates an array whose size is the initial value of i. But i is undefined at this stage so this is meaningless.
But i isn't relevant here anyway. How big do you want this array to be? The answer is number, isn't it? That is the number of people you'll store in your array.
So, a small improvement is to do this instead of int marks[i].
int marks[number];
But even this isn't correct. The value of number isn't set until the line cin >> number;, therefore you must declare int marks[number] after the line cin >> number; in order to ensure that marks has the correct size.
But, but, but, even after all this, we still don't have standard C++. It's OK to do int credit[7][2] because the size is fixed at compile time. You are normally not allowed to set the size of an array at runtime, e.g. int marks[number]. You might be able to use it if your compiler allows this extension (it's called Variable Length Array, from C).
So, this is not standard C++, and it's potentially very dangerous (see the Undefined Behaviour). What's the solution?
The solution is the standard solution for any problem involving arrays. Stop using arrays. (Really advanced programmers, in particular situations, might use std::array in modern C++, or even write their own clone of std:: array in older C++. But raw C [] arrays are to be avoided where possible.)
#include<vector>
int o,i,ttlcredit=0;
std::vector<int> marks;
marks is initially empty. We don't do cin >> marks[i];. Instead we use push_back to append new items to the end of the list.
int next_mark;
cin >> next_mark;
marks.push_back(next_mark);
Also, don't use marks[i] with a vector. It might look OK, but it is dangerous. Better to use marks.at(i) to read or write the element. at will do bounds checking for you, giving you a proper error message if i is too small (less then 0) or too big for the size of the vector.
int o,i,marks[i],ttlcredit=0;
i is not initialized. initialize i first.
If you are not sure of the size of the array, allocate it dynamically.
use new
refer this link on how to use new - cpluspluss
Related
This question already has answers here:
Why is it that we can write outside of bounds in C?
(7 answers)
Is accessing a global array outside its bound undefined behavior?
(8 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 11 months ago.
I wrote a code for entering element and displaying the array at the same time. The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements? Code:
#include <iostream>
using namespace std;
void display(char arr[],int n)
{
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
return;
}
int main()
{
char A[4];
int i=0;
char c;
for(;;)
{
cout<<"Enter an element (enter p to end): ";
cin>>c;
if(c=='p')
break;
A[i]=c;
i++;
display(A,i);
system("clear");
}
return 0;
}
Writing outside of an array by using an index that is negative or too big is "undefined behavior" and that doesn't mean that the program will halt with an error.
Undefined behavior means that anything can happen and the most dangerous form this can take (and it happens often) is that nothing happens; i.e. the program seems to be "working" anyway.
However maybe that later, possibly one million instructions executed later, a perfectly good and valid section of code will behave in absurd ways.
The C++ language has been designed around the idea that performance is extremely important and that programmers make no mistakes; therefore the runtime doesn't waste time checking if array indexes are correct (what's the point if the programmers never use invalid ones? it's just a waste of time).
If you write outside of an array what normally happens is that you're overwriting other things in bad ways, possibly breaking complex data structures containing pointers or other indexes that later will trigger strange behaviors. This in turn will get more code to do even crazier things and finally, some code will do something that is so bad that even the OS (that doesn't know what the program wants to do) can tell the operation is nonsense (for example because you're trying to write outside the whole address space that was given to the process) and kills your program (segfault).
Inspecting where the segfault is coming from unfortunately will only reveal what was the last victim in which the code is correct but that was using a data structure that was corrupted by others, not the first offender.
Just don't make mistakes, ok? :-)
The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements?
The code has a bug. It will not work correctly until you fix the bug. It really is that simple.
This question already has an answer here:
Array[n] vs Array[10] - Initializing array with variable vs numeric literal
(1 answer)
Closed 12 months ago.
What i would like to do is declare an array with "dim" size :int A[dim];.
Now, this works if I declare something like const int dim = 1 but doesn't with const int dim = round(x);, which is what i need to do. (Where x comes from cin >> x.)
Note: With "doesn't work" i refer to Visual Studio Code throwing red wavy line under dim in int A[dim]; and displaying the following when hovering it with my mouse:
`
expression must have a constant valueC/C++(28)
main.cpp(15, 11): the value of variable "dim" (declared at line 13) cannot be used as a constant
`
This is the relevant code:
#include <iostream>
using namespace std;
int main(){
float x;
cin >> x;
const int dim = round(x);
int A[dim];
int i = 0;
}
}
Given the context i believe the error is caused by one of two reasons:
Some characteristic of round() that makes the const int dim = round(x) not recognized as constant from the array later.
The problem is the x and not the round() so cin >> x is the reason.
[Thanks for whoever can explain me what I'm missing or point to some documentation that does. I have done some research but I haven't found a solution to this. Also this is my first question on SO, so tell me if I should change/improve something]
EDIT: Apparently the problem isn't in the round(x) as I previously thought because simply replacing const int dim = round(x); with const int dim = x; gives the same "error".
So the problem has to do with cin >> x .
EDIT 2 Note: I'm looking for a solution that doesn't use std::vector. We haven't studied it yet in the course so I believe the algorithm(from which i took the relevant code) shouldn't comprehend it.
Final Edit I didn't realize that, as #paulmckenzie clarified, using cin made the array dynamic because the imput comes in runtime, it was a really stupid error but I apologize, I'm really a beginner. In my defense we really haven't talked about dynamic size arrays so I guess that's what threw me off. I realized from the beginning I was missing something very basic, sorry for wasting time, I'll put even more time analyzing everything before posting next time.
The size of an array variable must be compile time constant in C++. User input is not compile time constant, hence it cannot be used as the size of an array variable.
In order to create an array with runtime size, you must instead create a dynamic array. The simplest way to do that is to use std::vector from the standard library.
EDIT 2 Note: I'm looking for a solution that doesn't use std::vector.
It's possible to create a dynamic array without std::vector, but that requires the use and understanding of more advanced concepts. Using new expressions directly is more difficult, error prone and is something that isn't (or shouldn't) be done in most programs in practice.
Of course, another solution is to just not use user input but rather an array with constant size.
I try to create an array. The size of it depends on the user's input. But how can I do it? or should I use string or vector instead?
I am new to C++. When I googled the problem, I still didn't get it. I tried the following code but it was not working.
const int t;
cin >>t;
double myarrary[t]={};
but my friends code works.
cin >> num;
int px[num]={};
Thank you
Variable length arrays like double myarrary[t] where t is a run-time value are a C feature. It is not in C++ standard, but some compilers do support that.
Use std::vector for portability.
I have a question regarding a school lab assignment and I was hoping someone could clarify this a little for me. I'm not looking for an answer, just an approach. I've been unable to fully understand the books explanations.
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n.
Assume that the array contains integers. The function should display
all of the numbers in the array that are greater than the number n .
This is what I have right now:
/*
Programmer: Reilly Parker
Program Name: Lab14_LargerThanN.cpp
Date: 10/28/2016
Description: Displays values of a static array that are greater than a user inputted value.
Version: 1.0
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void arrayFunction(int[], int, int); // Prototype for arrayFunction. int[] = array, int = size, int = n
int main()
{
int n; // Initialize user inputted value "n"
cout << "Enter Value:" << endl;
cin >> n;
const int size = 20; // Constant array size of 20 integers.
int arrayNumbers[size] = {5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // 20 assigned values for the array
arrayFunction(arrayNumbers, size, n); // Call function
return 0;
}
/* Description of code below:
The For statement scans each variable, if the array values are greater than the
variable "n" inputted by the user the output is only those values greater than "n."
*/
void arrayFunction(int arrayN[], int arrayS, int number) // Function Definiton
{
for (int i=0; i<arrayS; i++)
{
if (arrayN[i] > number)
{
cout << arrayN[i] << " ";
cout << endl;
}
}
}
For my whole answer I assume that this:
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n. Assume that the array contains integers. The function should display all of the numbers in the array that are greater than the number n .
is the whole assignment.
void arrayFunction(int[], int, int); is probably the only thing you could write. Note however that int[] is in fact int*.
As others pointed out don't bother with receiving input. Use something along this line: int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};. It will create static array for you;
You have parameter int n but you never use it.
You are trying to send variable to the function arrayFunction but I can't see definition of this variable!
Use something called rubber duck debugging (google for it :) ). It will really help you.
If you have some more precise question, ask them.
As a side note: there are better ways of sending an array to the function, but your assignment forces you to use this old and not-so-good solution.
Would you use an if else statement? I've edited my original post with the updated code.
You have updated question, then I update my answer.
First and foremost of all: do indent your code properly!!!
If you do that, your code will be much cleaner, much more readable, and it will be much easier understandable not only for us, but primairly for you.
Next thing: do not omit braces even if they are not required in some context. Even experienced programmers only rarely omit them, so as a beginner you should never do so (as for example with your for loop).
Regarding if-else statement the short answer is: it depends.
Sometimes I would use if (note: in your case else is useless). But other times I would use ternary operator: condition ? value_if_true : value_if_false; or even a lambda expression.
In this case you should probably settle for an if, as it will be easier and more intuitive for you.
Aside from the C++ aspect, think about the steps you need to do to figure out if a number is greater than a certain value. Then do that for all the numbers in the array, and print out the number if it's greater than n. Since you have a 'for' loop, it looks like you already know how to do a loop and compare numbers in C++.
Also, it looks like in your arrayFunction you are trying to input values? You can't input a whole array's worth of values in a single statement like you appear to be trying (also, 'values' is not the name of any variable in arrayFunction, so that would not be recognized when you try to compile it).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
It's a B problem in codeforces
http://www.codeforces.com/problemset/problem/598/B
and i submit this code, but i get Wrong Answer.
It's brute force nothing special, but iam new at problem solving.
#include <iostream>
#include<string>
using namespace std;
int main()
{
char x[10000];
scanf_s("%s",x);
int num;
scanf_s("%d",&num);
int *l = new int[num];
int *r = new int[num];
int *k = new int[num];
for(int i =0;i<num;i++)
{
scanf_s("%d,%d,$d",&l[i],&r[i],&k[i]);
}
char temp;
for(int i =0; i<num;i++)
{
for (int j =0;j<k[i];i++)
{
temp= x[l[i]-1];
x[l[i]-1]=x[r[i]-1];
x[r[i]-1]=temp;
}
}
printf("%s",x);
return 0;
}
Any idea what is wrong or does it need to be optimized ?Is there better way to handle with case of many queries entered ?
scanf is a C function. string is a C++ data type. C++ can often use C datatypes, but it is very rare that C can use C++ datatypes. scanf was written about 20 years before C++ existed and has no clue what a string is.
Next, scanf takes a variable arguments list. It has no clue if the parameter types are correct and cannot easily check. It assumes that the programmer knows what they are doing.
End result, it tries to place char data as specified by the %s format option into a string. The string is written over with incompatible data and undefined behaviour occurs.
Replace the scanf with
cin >> x;
and go all C++. Alternative is to eschew C++ and go C style:
char x[appropriate size goes here];
scanf("%s",x);
Don't know the appropriate size? That's going to be a problem. string resizes to fit. The char array expected by scanf cannot. If you read more data than you can fit, Undefined Behaviour.
In
scanf("%d",num);
%d says the programmer passed in a pointer to an integer, in this case it would be the location of num so that scanf can update the value stored at num with whatever was read. The value of num was passed in. scanf assumes this is a pointer and Undefined Behaviour results. Most likely whatever uninitialized garbage value that is in num is used as a memory location and some unsuspecting block of memory gets overwritten. This will cause problems at some point in the future when you actually need the data that was at that memory.
scanf("%d",&num);
or in C++
cin >> num;
The remaining problems are variations on the preceding two problems.
scanf("%d,%d,%d",l[i],r[i],k[i]);
needs pointers
scanf("%d,%d,%d",&l[i],&r[i],&k[i]);
and
printf("%s",x);
wants a char array, not a string.
printf("%s",x.c_str());
gets the char array equivalent to the string.
Recommendation: Compile with a higher level of intolerance to errors that the compiler can survive. In g++ I use at least -pedantic -pedantic-errors -Wall -Wextra -Werror.
On a logical front, your input is all unchecked. A user could type in "rutabaga" for num with possibly comical results as your program tries to deal with non-numeric input. Again Undefined Behaviour. The program could crash. It could lock up. It could impregnate a male Llama.
In C++
if (cin >> num)
will catch some but not all forms of bad input. If this test fails, the contents of num are undefined and should not be used. Further, the stream will be in an error state and unreadable until the error is acknowledged and cleared. In C the equivalent is
if (scanf("%d",&num) == 1)
if scanf read exactly one value, num, all is good. Any other number of values read means scanf did not succeed and the contents of num are undefined.