How to make an array of pointers and make the user enter the size of it? - windows-10

I want to make an array, and inside this array there are pointers, like this:
int *arrp[size]; and I want the user to enter the size of it.
I tried to do this:
#include <iostream>
using namespace std;
int main ()
{
int size;
cout << "Enter the size of the array of pointers" << endl;
cin >> size;
int *arrp[size];
return 0;
}
but this doesn't work.
I also tried to do this:
#include <iostream>
using namespace std;
int main ()
{
int size;
cout << "Enter the size of the array of pointers" << endl;
cin >> size;
int* arrp[] = new int[size];
return 0;
}
also doesn't work, can someone help?
The error of the first code is that the size must be constant, I tried to fix that by writing the 2nd code but it gives an error for the word "new" in line 9:
E0520 initialization with '{...}' expected for aggregate object
and another error for the size in the same line:
C2440 'initializing': cannot convert from 'int *' to 'int *[]'

To make an array of pointers you should type: int** arr = new int*[size]
we type 2 stars '*', the first mean a pointer to an integer, the second means a pointer to the pointer to the integer, and then we make a place in the memory for those pointers by typing = new int*[size], you can use this as a 2D array that stored in the heap (not the stack) go to this website to know the difference: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/.
to know more about how to use an array of pointers to a pointer to an integers you can see this video: https://www.youtube.com/watch?v=gNgUMA_Ur0U&ab_channel=TheCherno.

Related

How to round a number to the nearest hundreath and make that display on a string in c++

I am working on a money program. Currently I am trying to make a part in the program that displays a list that shows every transaction that was made in the session. My problem is that when I convert the money amount to a string instead of displaying something like 100.35 in when converted to a string it instead displays something like 100.35000000. I was wondering if there was any way I could make the program drop the additional zeros? Here is a sample of how I convert the numbers to a string
int main(){
double samplemoney=100.35;
string sample="Today we made $";
string comsample;
comsample=sample+std::tostring(money)+".";
cout<<comsample<<endl;
return 0;
}
In my main program this part is handled with a class but as I said earlier it seems like no matter what the money value I put in is it will display a series of zero and I want my program to drop the unnecessary zeros.
Let's say you have this number:
double number = 190.0391000;
If the problem is displaying the value you may use
std::cout << std::setprecision(5) << number
where f is the number you want to show.
If your problem is having a string with a finite precision you can use sprintf() in the following way:
char arr[128];
sprintf(arr,"%3.2f", number);
std::string formattedstring(arr);
or in a more C++ oriented way something like this
std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;
and then you get the string in the following way:
std::string formattedstring = strn.str();
I attach the full text of program here... tested on my machine:
#include <sstream>
#include <iostream>
int main() {
float number=100.24324232;
std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;
std::cout << strn.str() << "\n";
return( 0 );
}

Why is value only changed when referenced as calling argument?

In this code:
#include <iostream>
int num1 = 0;
using namespace std;
void add(int &number);
int main()
{
int num2;
int num3;
add(num1);
cout << "Num1 is: " << num1 << ". Yep, " << num1 << ".";
}
void add(int &number)
{
number++;
}
The passed value "num1" to "add" will change it, but in this code:
#include <iostream>
int num1 = 0;
using namespace std;
void add(int number);
int main()
{
int num2;
int num3;
add(num1);
cout << "Num1 is: " << num1 << ". Yep, " << num1 << ".";
}
void add(int number)
{
number++;
}
It does not change, the value of "num1". Why is that?
In the second case, you increment a COPY of the paramter. In the first case, with the "reference", you modify the variable itself.
Look up "pass by value vs pass by reference. For example:
Pass by reference
Call by value
It should be noted that C (unlike C++) is always "pass by value" ... but the equivalent can be achieved by passing a pointer to a variable.
In the first case number is a reference to num1. That is that number is reference to the same place in memory num1 refers to. Similar to a pointer but without the hassle of dereferencing it.
In the second number is created in the activation record of add, and placed on the stack. When add terminates the number variable is poped off (and the memory of number is deallocated) the stack, and num1 is left unchanged in main's stack and activation record.
If it were an object and not a primitive, this could be seen in the debugger by where the segfault would occur if you were to manually called the destructor just before add returned.

Having trouble passing array to function

I am getting all kinds of errors when passing my array to this function. The function is suppose to have the user enter a name and a score and store them in 2 seperate arrays, one for the names, one for the scores. I believe I have to use pointers but have no idea on how to use them. I don't want the answer, just a push in the right direction. Here is the code:
#include <iostream>
int InputData(int &, char, int);
using namespace std;
int main()
{
char playerName[100][20];
int score[100];
int numPlayers = 0;
InputData(numPlayers, playerName, score);
return 0;
}
int InputData(int &numPlayers, char playerName[][20], int score[])
{
while (numPlayers <= 100)
{
cout << "Enter Player Name (Q to quit): ";
cin.getline(playerName, 100, ā€˜\nā€™);
if ((playerName[numPlayers] = 'Q') || (playerName[numPlayers] = 'q'))
return 0;
cout << "Enter score for " << playerName[numPlayers] <<": ";
cin >> score[numPlayers];
numPlayers++;
}
}
Ok, I made some more changes and the errors are less, must be getting close, Lol!
This looks like a school assignment and I applaud you for not asking for the answer. There are several ways to do it, but you are already fairly close in the approach that you are using. When you pass an array reference, you do not want to include the length of the array. For example, the parameter int score[100] should be int score[]. The exception, especially in your scenario, is with multidimensional arrays. In this case, you want to use char playerName[][20]. Your function declaration also needs to change to match. Don't forget InputData returns an int. Your declarations and function call are correct; you just need to adjust your function signature.
Keeping the errors aside -
InputData(numPlayers, playerName, score, size);
// ^^^^ size is no where declared
// resulting Undeclared indentifier error
Prototype mentions of taking 3 arguments but calling the function passing 4 parameters.
Hint regarding errors:
An 1D array decays to a pointer pointing to first element in the array while passing to a function.
A 2D array decays to a pointer pointing to the 1D array ( i.e., T[][size] ) while passing to a function.
Return type of main() should be int.
It seems with the given hints you corrected most of the errors. But you forgot to change the prototype. So, change -
int InputData(int &, char, int);
to
int InputData(int &, char[][20], int[]);
Why aren't you using std::string array for player names ? Use it and remove rest of the errors. Good luck.

VC++ read variable length char*

I'm trying to read a variable length char* from the user input. I want to be able to specify the length of the string to read when the function is called;
char *get_char(char *message, unsigned int size) {
bool correct = false;
char *value = (char*)calloc(size+1, sizeof(char));
cout << message;
while(!correct) {
int control = scanf_s("%s", value);
if (control == 1)
correct = true;
else
cout << "Enter a correct value!" <<endl
<< message;
while(cin.get() != '\n');
}
return value;
}
So, upon running the program and trying to enter a string, I get a memory access violation, so I figured something has gone wrong when accessing the allocated space. My first idea was it went wrong because the size of the scanned char * is not specified within scanf(), but it doesn't work with correct length strings either. Even if I give the calloc a size of 1000 and try to enter one character, the program crashes.
What did I do wrong?
You have to specify the size of value to scanf_s:
int control = scanf_s("%s", value, size);
does the trick.
See the documentation of scanf_s for an example of how to use the function:
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size is passed as an additional parameter immediately following the pointer to the buffer or variable.
I omit the rest of the MSDN description here because in the example they're providing, they use scanf instead of scanf_s what is quite irritating...

Reading a value in associative array creates a new key

I have code such as this. I use
pvalueholder is class that is polymorphic , it can hold all sort of types, string..etc..
It also can have a type undefined.
typedef hash_map<pvalueholder,pvalueholder,pvaluehasher > hashtype;
hashtype h;
pvalueholder v;
v="c";
h[v]=5; // h has one element
pvalueholder v2=h[v]; // here h gets a new key/value how is that possible?
cout << (string) (h[v]) << endl; // here h gets another new key/value how is that possible?
int i =0;
for (hashtype::iterator h1=h.begin(); h1!=h.end();h1++)
{
cout << "no: " << i++ << endl;
} // this prints three lines, it should print one...
Two values are undefined here, the third one is 5 as expected.
size_t pvaluehasher::operator() (const pvalueholder& p) const
{
cout << "hashvalue:" << p.value->hashvalue() << endl;
return p.value->hashvalue();
}
returns
Here is what is printed:
hashvalue:84696444
hashvalue:84696444
hashvalue:84696444
returns:1
hashvalue:84696444
returns:1
hashvalue:84696444
returns:1
returns:1
hashvalue:84696444
Do you have any ideas what it may be?
Thank you.
Solution:
the function operator()(parameter1,parameter2) needs to be different in case of Microsoft STL.
For microsoft, it needs to return less than relationship between parameter1 and parameter2.
For gcc, it needs to return equality. I returned equality.
The comparison function for the keys was not correct...
The function returned true for equality while it has to return less than in case of Microsoft STL.
My guess would be that your hash function is incorrect - meaning it produces different hash values given the same key "c".
Show the declaration for pvalueholder and full code for pvaluehasher.
It's almost impossible to comment on hash_map, because it's never been standardized, and the existing implementations aren't entirely consistent. Worse, your code doesn't seem to be correct or compilable as it stands -- some places the value associated with the key seems to be an int, and other places a string.
Using std::tr1::unordered_map and fixing the rest of the code to compile and seem reasonable, like this:
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
typedef std::tr1::unordered_map<std::string, int> hashtype;
std::ostream &operator<<(std::ostream &os, std::pair<std::string, int> const &d) {
return os << d.first << ": " << d.second;
}
int main() {
hashtype h;
std::string v = "c";
h[v]=5; // h has one element
int v2=h[v];
cout << h[v] << endl;
int i =0;
for (hashtype::iterator h1=h.begin(); h1!=h.end();h1++)
{
cout << *h1 << endl;
} // this prints three lines, it should print one...
return 0;
}
The output I get is:
5
c: 5
This seems quite reasonable -- we've inserted only one item, as expected.
Solution: the function operator()(parameter1,parameter2) needs to be different in case of Microsoft STL. For microsoft, it needs to return less than relationship between parameter1 and parameter2. For gcc, it needs to return equality. I returned equality. The comparison function for the keys was not correct... The function returned true for equality while it has to return less than in case of Microsoft STL.

Resources