Displaying numbers from a user created array c++ [duplicate] - c++

This question already has answers here:
getting size of array from pointer c++
(6 answers)
Closed 7 years ago.
Alright so this is probably a really simple question, I'm just really new to c++ and am struggling to understand most things. I've been asked to create an array that stores random numbers but the user is to define the size of the array. I then have to display all the numbers in the array. What I'm struggling with is displaying all elements of the array. At the moment, I'm pretty sure I've got the array part down, but I can only seem to display one number. Here's my code so far:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
using std::srand;
using std::rand;
using std::time;
void Display(int *, int);
int main(void)
{
int userSize;
cout << "Please enter the size of the array: ";
cin >> userSize;
int* randArray = new int[userSize];
srand(time(NULL));
for (int i = 0; i < userSize; i++) {
randArray[i] = rand() % 20 + 1;
}
//Disregard the next few lines, I was just testing to see if anything was actually in the array.
/*cout << randArray[0] << endl;
cout << randArray[1] << endl;
cout << randArray[2] << endl;
cout << randArray[19] << endl;*/
Display(randArray, sizeof(randArray) / sizeof(int));
return 0;
delete[] randArray;
}
void Display(int *arrayData, int numElements)
{
for (int counter = 0; counter < numElements; counter++)
{
std::cout << *(arrayData + counter) << std::endl;
}
return;
}
I should also mention that the teacher provided us with the code after the line that deletes the array.
This is the question I have to answer: Ask the user for the number of elements to be stored in the array. You should then dynamically allocate the memory to hold this array, which will proceed to be used in the same way as the previous task (populating the array with random data, displaying the data to the
screen).

sizeof(randArray) does not tell you the number of bytes that you've allocated. Rather, it tells you the size of a pointer, which on your system happens to be the same as the size of an integer, so sizeof(randArray) / sizeof(int) returns 1 always. Instead use userSize as your second parameter in the function call to Display.
Also, you delete[] randArray after return 0. This is incorrect; nothing after the return 0 will be executed. You want it above instead.
Further, consider the use of std::vector instead (unless you are required to use a raw pointer for this assignment)

The problem is sizeof. It gives you the size of the type of the argument, not of what is behind. Your should pass userSize to Display().
You should also delete the array before you return. Code behind return never gets executed.

Related

How can I discover the amount of elements in an array in C++ [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
C sizeof a passed array [duplicate]
(7 answers)
Closed 4 years ago.
I'm facing some problems with my code in C++. I would like to know how can I discover the amount of elements in an array. Follow the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int avg(int numbers[]){
int amount; // The problem is in. How can I discover the amount of elements in an array?
int sum = 0;
for(int i = 0; i < amount; i++){
sum += numbers[i];
}
return sum / amount;
}
int main(){
int q;
cout << "Type number of integers:" << endl;
cin >> q;
int numbers[q];
for(int i = 0; i < q; i++){
cout << "Type an integer value for number " << i+1 << ":" << endl;
cin >> numbers[i];
}
cout << "The average is " << avg(numbers) << endl;
return 0;
}
The standard array in C++ doesn't contain a way to access the size of the array, the best way to track this is to have an integer that is updated with the size of the array or to try using std::array and then use the .size() method.
In your example you are using a fixed size array anyway so you may want to store the q value as a member variable and that contains the array size. Notice that in your example the code will not work as q is not a constant integer. To declare an array without a constant integer you will need to use a pointer to the first element of the array ie: int* numbers = new int[q];.

How to return an array from a function in c++ [duplicate]

This question already has answers here:
Return array in a function
(20 answers)
Closed 4 years ago.
I'm really confused on the theory behind this. Not sure how to return the array from my isAscending function so i can print out in the main.
#include <iostream>
#include <string>
using namespace std;
// Implement printArray here
void printArray(int array[], int n){
for (int i = 0; i < n; ++i )
cout << array[i] << endl;
};
// Implement isAscending here
int isAscending(int array[], int n){
for(int i = 0; i <= n; ++i){
for(int j = 0; j <= n; ++j){
if(array[i] > array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
return printArray(array, n);
};
// DO NOT CHANGE MAIN FUNCTION BELOW
int main() {
int myarray[100];
cout << "Enter number of integers : ";
int n;
cin >> n;
cout << "Enter " << n << " integers" << endl;
for (int i = 0; i < n; i++)
cin >> myarray[i];
cout << "Contents of array : ";
printArray(myarray, n);
cout << "Output of isAscending: " << isAscending(myarray, n) << endl;
}
Should I use pointers to pass the elements in the array i am stuck.
The short answer is you don't. When you pass an array to a function, you're actually just passing a pointer to the first element (the array decays to a pointer when you pass it as an argument). This means that if you modify the array in the function, you're modifying the original array and not a copy. Therefore, your isAscending() function will bubble sort the array you called it on and it does not need to return anything.
Just a side note, it seems like the assignment simply wants you to check if an array is ascending, instead of sorting it. In that case, isAscending() should return a bool.
If you need a function to return an array, you can't just pass a pointer to the first element since the array goes out of scope as soon as the function returns. You could dynamically allocate the array, but that just creates a bunch of new problems. Another way might be to return the pointer to the first element of the array passed to it as an argument like this, but there isn't much point in doing that since the caller already has access to the array.
The best way would be to use something like std::array or std::vector, which you can return by value just like any other variable. I would also recommend getting a good book.
(I provided this answer besides flagging as a duplicate since I thought the answer of the duplicate question was not complete enough and might mislead someone into trying to return a pointer to a local array)

C++ My program has confused me greatly [closed]

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 6 years ago.
Improve this question
Here it is:
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>
using namespace
int main()
{
//cout << "How many players?" << endl;
int numplayers=1;
//cin >> numplayers;
int players[numplayers];
int x=0,y=0;
srand(time(0));
x=(rand() % 6 + 1);
y=(rand() % 6 + 1);
players[1]=players[1]+x+y;
cout << ("Your score is" + players[1]) << endl;
cin >> numplayers;
}
Ok My original problem was that this always crashed, now it prints "#"???
C++ arrays are 0 based.
players[1] is accessing a location outside the range of the array.
You will want: players[0].
cout << ("Your score is" + players[1]) << endl;
Here you're trying to use direct string concatenation, but you can't concatenate a string literal with an integer like that. You end up doing pointer arithmetic, which is definitely not what you intended.
You should instead use cout's built-in formatting:
cout << "Your score is" << players[1] << endl;
Your next problem is that players is not declared correctly; an array cannot have runtime bounds, and numplayers (despite having only the one initial value) is ultimately a "runtime" variable. You would be better off with a std::vector if the size of the array is going to change later; otherwise make numplayers a constexpr.
Your last problem is that, if the array declaration were valid, you'd be trying to access the second element of a one-element array! The first element is players[0], not players[1].
There are many things you're doing not good.
I believe you're using C++, there is no known way to me about creating arrays of dynamic size i.e. int players[numplayers]. In C++ either we can create array of fixed size i.e. int players[10] or use pointer to an array for dynamically allocated memory e.g. int* players = new int[numplayers]. This allocates an array of size numplayers and an int pointer named players is pointing to it. We can use this pointer as normal array e.g. printing 1st index of array is written as player[0] or another syntax is *(player + 0). Remember to delete this dynamically allocated memory at the end of program i.e. delete[] player.
Second thing is when you have allocated an array and are using its value for computation, always initialize it to 0 as newly allocated array contains garbage value and it will affect your computations. code for initializing it to zero may be like this:
Here is the loop:
for(int i = 0 ; i < numplayers ; i++){
player[i]=0;
//another syntax is : *(player + i) = 0;
}
C++ does not concat as you did in your std::cout statement. Make it like this:
cout << "Your score is" << players[0] << endl;
In C++, arrays always start with index zero, so 1st index will be 0 in this case. So your program will work well if it is like this:
int numplayers = 1;
int* players = new int[numplayers];
int x = 0, y = 0;
srand(time(0));
x = (rand() % 6 + 1);
y = (rand() % 6 + 1);
players[0] = 0;
players[0] = players[0] + x + y;
cout << "Your score is" << players[0] << endl;
delete[] players;
return 0;
Definitely it crashes for the below line:
players[1]=players[1]+x+y;
Because size of players array is 1, so it has only index 0. And in above line, it tries to access index 1. Take a look at Buffer Overflow and array index out of bounds.
Try to define an array with constant size.
If you need a dynamic array, use linked list or vector.

Using C++ how many characters are in a string array?

I have the below piece of code and I'm very confused by it. I'm trying to figure out how much memory (bytes of memory/space is actually being taken up by my partially filled array). I've got the below piece of code but I'm a bit confused.
If I declare a string array of 8 elements, and partially fill the elements with the two strings. The for loop will start at 0 and go until size of my array 32 possible bytes (assuming I need 4 bytes per string) divided by size of the first element in the array. That is returns 4 - the size of the element of the first string in the array. But that still doesn't tell me how many letters/characters are in that string.
I understand inside the loop we increment count when the value in the array doesn't equal a blank/null value. Giving us the total filled (non empty) positions in our array. However I still don't have a value for our actual amount of characters.
How does this tell us how many characters are in my strings?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test_array[8] = {"henry", "henry2"};
size_t count = 0;
for (size_t i = 0; i < sizeof(test_array)/sizeof(*test_array); i++)
{
cout << "NOT THE POINTER: "<<sizeof(test_array) << endl;
cout << "POINTER: "<<sizeof(*test_array) << endl;
if(test_array[i] != "")
count ++;
}
int num_elem = sizeof(test_array)/sizeof(test_array[0]);
cout << num_elem << endl;
cout << count << endl;
return 0;
}
To know how many characters are in a std::string use the size() method.

How to get the size of the used space in an array? (NOT sizeof); c++

#include<iostream>
using namespace std;
int main()
{
char arr[200];
while(1) {
cin >> arr;
int i = sizeof(arr);
cout << "The arr input is "<< arr
<< " and the size of the array is "<< i << endl;
}
return 0;
}
For the input of 34,
This code outputs :The arr input is 34 and the size of the array is 200
while I want it to get the size of the used space of the array . So for The last input i want it to output :The arr input is 34 and the size of the array is 2
Can someone tell me how?
Maybe you want strlen(arr) here. It must be null terminated, otherwise the cout << arr would not have worked.
You would need to #include <cstring>
There's no automatic way to do what you want in the general case - you'll need to keep track somehow, either with your own counter, or by seeding the array with an 'invalid' value (that you define) and search for to find the end of the used elements (that's what the '\0' terminator character in a C-style string is).
In the example code you posted, the array should receive a null terminated C-style string, you can use that knowledge to count the number of valid elements.
If you're using C++ or some other library that has some more advanced data structures, you may be able to use one that keeps track of this kind of thing for you (like std::vector<>).
the size of the used space of the array
There is no such thing. If you have an array of 200 chars, then you have 200 chars. Arrays have no concept of "used" and "unused" space. It only works with C-strings because of the convention that those are terminated by a 0 character. But then again, the array itself cannot know if it is holding a C-string.
in a less involved manner, you can just count through each character till you hit a null with just a while loop. It will do the exact same thing strlen() does. Also, in practice, you should do type checking with cin, but i'll assume this was just a test.
#include <iostream>
using namespace std;
int main()
{
char arr[200];
int i;
while(1) {
cin >> arr;
i=0;
while (arr[i] != '\0' && i<sizeof(arr))
i++;
cout << "The arr input is "<< arr
<< " and the size of the array is "<< i << endl;
}
return 0;
}
Just for completeness, here is a much more C++ like solution that is using std::string instead of a raw char array.
#include <iostream>
#include <string>
int
main()
{
while (std::cin.good()) {
std::string s;
if (std::cin >> s) {
std::cout
<< "The input is " << s
<< " and the size is " << s.length()
<< std::endl;
}
}
return 0;
}
It doesn't use an array, but it is the preferable solution for this kind of problem. In general, you should try to replace raw arrays with std::string and std::vector as appropriate, raw pointers with shared_ptr (scoped_ptr, or shared_array, whatever is most appropriate), and snprintf with std::stringstream. This is the first step to simply writing better C++. You will thank yourself in the future. I wish that I had followed this advice a few years ago.
Try it
template < typename T, unsigned N >
unsigned sizeOfArray( T const (&array)[ N ] )
{
return N;
}