Read the grade of students by Array C++ [duplicate] - c++

This question already has answers here:
Why no variable size array in stack?
(7 answers)
Closed 8 years ago.
This simple program to read the grade of students. I want to take how many students the user want to enter, but when I'm writing int g[size];it will be compilation error! I wonder how can I write it correct?
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter how many student ..? ";
cin >> x;
const int size = x;
int g[size];
cout << "enter " << size << "your ";
for (int i = 0; i < size; i++){
cin >> g[i];
}
for (int i = 0; i < size; i++){
cout << "student" << i + 1 << "grade is : " << g[i] << endl;
}
system("pause");
return 0 ;
}

The line int g[size]; causes a compile error because size is not known at compile time (but obviously at runtime).
So you need to allocate memory for the array at runtime.
int *g = new int[size]; // instead of int g[size];
This stores a pointer to the first element of the array in g. Now the compiler can no longer track the lifetime of the array and delete it for you when it isn't needed anymore so you need to do this yourself as well.
delete[] g; // this frees the memory again
system("pause");
As a side note: Your program is valid C++14 which is not yet (fully) supported by Microsoft's Visual C++ compiler but other compilers like clang and g++ already support it.

Related

free or delete array of strcut c++

I made a simple array of struct I made a function to implement the array from users input
but I am struggling to find the right way to free or delete elements in the array ;
here is my code for a better understanding
#include <iostream>
using namespace std;
typedef struct InfStudent
{
int id;
int age;
int lvel;
}studentInfo;
void addElments(studentInfo *s)
{
int i=0;
for(i=0; i<2; i++) {
s[i].id = i;
s[i].age = i * i + 1;
s[i].lvel = i + i + 2;
}
}
int studCounter = 0 ;
void deltetElement(void *studentInfo1 ) {
for (int i = 0; i < 6; i++) {
cout << "empty " << endl;
free(studentInfo1);
}
}
int main()
{
int n;int i;
studentInfo st[2];
addElments(st);
for(i=0; i<2; i++) {
cout<<"enter the Id number of the student "<< endl;
cin >> st[i].id;
cout<<"enter the age of the student "<< endl;
cin >> st[i].age;
cout<<"enter the level of the student "<< endl;
cin >> st[i].lvel;
}
deltetElement(st);
for(i=0; i<2; i++) {
cout << "Id of the student " << i << "\t=" << st[i].id;
cout << "\t Age of the student " << i << "\t=" << st[i].age;
cout << "\tLevel of the student " << i << "\t=" << st[i].lvel;
cout<< endl;
}
return 0;
}
the output
enter the Id number of the student
1234
enter the age of the student
32
enter the level of the student
2
enter the Id number of the student
321
enter the age of the student
2
enter the level of the student
32
empty
it is printing empty, but the code still working like 3 second and then printing empty massage, but I did not understand it does delete or not, or there is a better way to do that;
Since you are using studentInfo st[2]; it's an array of VALUE types, meaning that studentInfo objects are not allocated in heap, and should not be deleted by free() or delete.
free or delete array of strcut c++
You create an array with automatic storage. Automatic objects are destroyed and their storage is released automatically when the variable goes out of scope. You cannot and you must not "free" them in any way other than by letting the execution proceed to the outside of the scope where the automatic object is defined.
Only thing that may be passed to free is a pointer that was returned by malloc (or certain other related C allocation functions) and hasn't previously been freed. Since that doesn't apply to what you pass to free, the behaviour of your program is undefined. That's bad. Don't do that.
P.S. Don't use malloc nor free in C++ if you can avoid it (and it can usually be avoided).
I am struggling to find the right way to free or delete elements in the array ;
The elements of an array are destroyed and their storage released when the array itself is destroyed and its memory is released. There is no way to separate those two.

How do I set an array size with a variable? C++ [duplicate]

This question already has answers here:
How to create an array when the size is a variable not a constant?
(6 answers)
Closed 5 years ago.
I've got some code that defines a variable called 'size' then uses it but for some reason it doesn't work ; the error is "Expression did not evaluate to a constant"
int main()
{
int size;
int userValue;
char input;
do
{
cout << "Enter an int for the size of the array:" << endl;
cin >> size;
int a[size];
cout << "Enter an integer between 1 and " << size << " to search for in the array." << endl;
cin >> userValue;
populateArray(a, size);
linearSearch(a, size, userValue);
binarySearch(a, size, userValue);
cout << "Press 'y' and enter to run again or just enter to quit";
cin.sync();
cin.get(input);
}while(input == 'y');
}
You can ignore the other functions as they are not called before the defining of my array, Ive tried setting size to a value, still doesn't work.
EDIT: forgot to mention
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
Why not use a vector?
std::vector<int> a(size);
Also in C++, you cannot define an array with a variable like that.
Alternative:
int* a = new int[size];
// Do stuff
delete [] a;

Stumped on array creation program

For a program I must use an array and not vector. I have to take in user's input, and it's a indefinite amount of them. The user can type in 5 values, or 50. I am absolutely stumped as to how to go about doing this. Using a for loop for example:
Int a[10];
Int b;
For (int i=0; i<10; i++)
{
Cout<<"enter values:";
Cin>>b;
A[i]=b;
}
With this I can take an array of 10 of user defined variables but how would I go about making it a dynamic size? Thank you for the help!
The size of a static array must be known at compile time, otherwise you must use a dynamic array. For example
#include <iostream>
int main()
{
// Determine how many total entries are expected
int entries;
std::cout << "How many values do you want to enter?" << std::endl;
std::cin >> entries;
// Allocate a dynamic array of the requested size
int* a = new int[entries];
// Populate the array
for (int i = 0; i < entries; ++i)
{
std::cout << "enter a value: ";
std::cin >> a[i];
std::cout << std::endl;
}
// Clean up your allocated memory
delete[] a;
return 0;
}

Console crashes outputting pointer array and iterations C++

I am busy working on a simple concept to display pointer arrays and iterations of a for loop in C++
My compiler is not giving much away and when I run the program the console is saying the following and returning 3 "The application has requested the Runtime to terminate in an unusual way.
The crash occurs on this line:
cout << i + 1 << " " << *(pArray + i) << endl;
but when I run this program ommiting either i + 1 or *(pArray + i) it runs without errors or crashing.
Is it illegal to try and output as I am trying to do above?
See below for the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int * pArray;
int SIZE;
int module;
pArray = new int[SIZE];
cout <<"Enter the number of Assignments ";
cin >> SIZE;
cout <<"input assignment number " ;
for (int i = 0; i < SIZE; i++)
{
cin >> module;
*(pArray + i) = module;
}
// Print array
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << " " << *(pArray + i) << endl;
}
cout << endl;
delete[] pArray; // Deallocate array via delete[] operator
return 0;
}
I am admittedly a little nervous to ask this question but I just need someone to explain why this is happening as I am battling to find any reference on this type of situation.
Thanks
You use SIZE two lines before you initialize it.
Move
pArray = new int[SIZE];
to after where you obtain the value of SIZE.
(Also: this would be so much easier with std::vector.)
int * pArray;
int SIZE;
int module;
pArray = new int[SIZE];
SIZE is not initialised yet, so, it would be some junk value.
Initialise it before using it.
You could also Check for success/failure of new.
pArray = new(nothrow) int[SIZE];
if(pArray)
//logic

segmentation fault with dynamic allocation and arrays/pointers

I'm working on an assignment that is introducing the principals of dynamic allocation of memory and pointers. I had made a simple program in the past that accepted 5 names and 5 scores and then used a selection sort to put them in descending order. My assignment now is to come back to that same program and ask the user how many scores they would like to input, then use pointers to dynamically allocate the necessary amount of memory. This is my first time working with pointers and these concepts so im still trying to figure it all out.
I got the code to compile but I get a segmentation fault error as soon as i enter any integer number for how many scores i would like to input (which is the first thing the program asks)
Im sure there are a few errors along the way with how i called and declared functions so if theres anything i just desperately change please let me know, but for now I dont understand why my program is crashing where it is crashing.
Here is my code
#include <iostream>
using namespace std;
void initializeData(string *names[], int *scores[], int num);
void displayData(string *names[], int *scores[], int num);
void sortData(string *names[], int *scores[], int num);
int main()
{
int num;
int **intPoint;
string **strPoint;
cout << "How many scores would you like to enter?: ";
cin >> num;
cout << " core dumped? ";
*intPoint = new int[num];
*strPoint = new string[num];
initializeData(strPoint,intPoint,num);
sortData(strPoint,intPoint,num);
displayData(strPoint,intPoint,num);
return 0;
}
void initializeData(string *names[], int *scores[], int num)
{
for(int i=0;i<num;i++)
{
cout << "Please input the name for score: " << i+1 << ": " << endl;
cin >> *(names[i]);
cout << "Please input the score for player: " << i+1 << ": " << endl;
cin >> *(scores[i]);
}
}
void sortData(string *names[], int *scores[], int num)
{
int minIndex,minValue,x;
string stringTemp;
for(int i = 0;i<(num-1);i++)
{
minIndex = i;
minValue = *(scores[i]);
for(x= i+1;x<num;x++)
{
if(*(scores[x]) > minValue)
{
minValue = *(scores[x]);
minIndex = x;
}
}
*(scores[minIndex])=*(scores[i]);
*(scores[i]) = minValue;
stringTemp = *(names[minIndex]);
*(names[minIndex]) = *(names[i]);
*(names[i]) = stringTemp;
}
}
void displayData(string *names[], int *scores[], int num)
{
cout << "Top scorers: " << endl;
for(int i=0;i<num;i++)
{
cout << names[i] <<": ";
cout << scores[i] << endl;
}
}
and my current output:
How many scores would you like to enter?: 10
Segmentation fault (core dumped)
which happens regardless of what int i put there. I put a cout statement after the
cin << num; to see if the program got that far but it never does.
Any help is greatly appreciated. Sorry if this is the most basic error ever.
int **intPoint;
At this point in your code, intPoint doesn't point to anything since you haven't assigned it a value.
*intPoint = new int[num];
Then you dereference it, but it doesn't point to anything.
Try:
int *intPoint;
intPoint = new int[num];
Now you are setting intPoint's value so that it points to the integers you allocated.
The reason you get a segmentation fault is because you dereference an uninitialized pointer.
int **intPoint; // intPoint is declared a pointer to a 'pointer to an int';
// but currently it points to nothing
*intPoint = new int[num]; // *intPoint "dereferences" intPoint, i.e., assigns w/e it
// pointed to (which is nothing) to a pointer.
Like the others have suggested, you didn't need a double pointer here.
int *intPoint; // intPoint is a pointer to an int
intPoint = new int[num]; // notice how we didn't dereference intPoint.
// all we did was assign to our newly minted memory.
Use std::vector in the place of array of int or string.
say,
std::vector<int> scores;
std::vector<string> names;
This way you can avoid all the hassles. This is simple and elegant.