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.
Related
I have come across a piece of example code that uses pointers and a simple subtraction to calculate the number of items in an array using C++.
I have run the code and it works but when I do the math on paper I get a different answer.
There explanation does not really show why this works and I was hoping someone could explain this too me.
#include <iostream>
using namespace std;
int main() {
int array[10] = {0, 9, 1, 8, 2, 7, 3, 6, 4, 5};
int stretch = *(&array + 1) - array;
cout << "Array is consists of: " << stretch << " numbers" << endl;
cout << "Hence, Length of Array is: " << stretch;
return 0;
}
From: https://www.educba.com/c-plus-plus-length-of-array/
When I run the code I get the number 10.
When I print the results of *(&array + 1) and array by
cout << *(&array+1) << endl; cout << array << endl;
I get of course two hex address's.
When I subtract these hex numbers I get 1C or 28???
Is it possible that C++ does not actually give the hex results or their translation to decimal but rather sees these numbers as addresses and therefore only returns the number of address slots remaining?
That is the closest I can come to an explanation if some one with more knowledge than I could explain this I would be very grateful.
Let's take one step back and take it step-by-step to see if it will help. Continuing from my comment, the problem you are having difficulty with is one of type.
Let's take the array iteself:
int array[10] = {0, 9, 1, 8, 2, 7, 3, 6, 4, 5};
On access, an array is converted to a pointer to the first element in the array (e.g. the address of the first element) subject to caveats not relevant here. So when you say array, you have type int *, a pointer to the first element in array.
Now what happens when I take the address of the array? (&array in)
int stretch = *(&array + 1) - array;
When you take the address of the array, the result is the same address as array, but has type int (*)[10] (a pointer-to-array-of int[10]). When you add 1 to that pointer (recall type controls pointer arithmetic), you get the address for the pointer to the next array of int[10] in memory after array -- which will be 10 int after the first element of array.
So *(&array + 1) gives you the address to the next array of int[10] after array, and then dereference is only needed for type compatibility. When you dereference an int (*)[10] you are left with int[10] -- which on access gives you the address of the first element of that array (one after the original)
Think through the types and let me know if you have further questions.
You forgot a small detail of how pointer addition or subtraction works. Let's start with a simple example.
int *p;
This is pointing to some integer. If, with your C++ compiler, ints are four bytes long:
++p;
This does not increment the actual pointer value by 1, but by 4. The pointer is now pointing to the next int. If you look at the actual pointer value, in hexadecimal, it will increase by 4, not 1.
Pointer subtraction works the same way:
int *a;
int *b;
// ...
size_t c=b-a;
If the difference in the hexadecimal values of a and b is 12, the result of this subtraction will not be 12, but 3.
When I subtract these hex numbers I get 1C or 28 ???
There must've been a mistake with your subtraction. Your result should be 0x28, or 40 (most likely you asked your debugger or compiler to do the subtraction, you got the result in hexadecimal and assumed that it was decimal instead). That would be the ten ints you were looking for.
I will try it with 5 items
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int array[] {1,2,3,4,5};
int items= sizeof(array)/sizeof(array[0]);
cout << items << endl;
int items2 = *(&array +1) - array;
cout << items2 << endl;
cout << array << endl;
cout << *(&array +1) << endl;
return 0;
}
root#localhost:~/Source/c++# g++ arraySize.cpp
root#localhost:~/Source/c++# ./a.out
5
5
0x7fe2ec2800
0x7fe2ec2814
using https://www.gigacalculator.com/calculators/hexadecimal-calculator.php to subtract the numbers from each other
I get
14 hex
20 decimal.
that fits with the 4 bytes to an integer.
thanx guys :)
this is an edit done on the 12th of december melbourne time ::
I have still had questions on this topic and something did not fit right with me about the entire route to counting array items via this code.
I found something I think is interesting and again would love to know why ( I shall try to explain it as best I can my self anyway)
*(&array + 1) is the question.
lets have a look at it.
as arrays are at there very nature in c and c++ only pointers to the first element in the array how can this work.
I shall use a small set of cout calls to see if I can find out whats happening.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
int array[] {1,2,3,4,5,6,7,8,9,10};
int size {0};
size = *(&array + 1) - array;
cout << "size = *(&array + 1) - array = " << size << endl;
cout << "*(&array + 1) = " << *(&array + 1) << endl;
cout << "(&array + 1) = " << (&array + 1) << endl;
cout << "(array + 1) = " << (array + 1) << endl;
cout << "&array = " << &array << endl;
cout << "array = " << array << endl;
cout << "*(&array) = " << *(&array) << endl;
cout << "*(array) = " << *(array) << endl;
cout << "*array = " << *array << endl;
return 0;
}
again this is off proot in my phone so still under root with no systemd.
root#localhost:~/Source/c++# g++ arrayPointerSize.cpp
root#localhost:~/Source/c++# ./a.out
size = *(&array + 1) - array = 10
*(&array + 1) = 0x7ff6a51798
(&array + 1) = 0x7ff6a51798
(array + 1) = 0x7ff6a51774
&array = 0x7ff6a51770
array = 0x7ff6a51770
*(&array) = 0x7ff6a51770
*(array) = 1
*array = 1
we see that as a pointer array can be called with * too derefernce the pointer and give the variable held in position [0] in the array.
when calling &array or reference too array we get the return of the address at the first position in the array or [0].
when calling just array we also get the address for the first position in the array or [0].
when calling *array the * is working as it does for pointers and it is dereferencing the arrays first position [0] to give the variable.
now things get a little interesting.
*(array) also dereferences the array as is seen by its value being given as 1 in this instance.
yet *(&array) does not dereference the array and returns the address to the first position in the array.
in this instance memory address 0x7ff6a51770 is the first spot in the array array = 0x7ff6a51770
and &array (reference to the pointer of the position in memory that is the first spot in the array) gives the same address 0x7ff6a51770.
it is also of note in this instance to remind us of the fact that *(&array) is also returning the first possition in the array and *(array) is not
so we can not dereference a pointer too a position in memory as its variable is the position in memory.
if array and &array give the same answer as array is a pointer too the memory position in the first spot in our array and a reference to
this pointer.
why the different answer for (array + 1) and (&array + 1).
we get the memory address 0x7ff6a51774 for (array + 1) which is in line with an integer taking four bytes on my linux or
the addition of four bytes in memory past the first spot in the array (second array spot) but (&array + 1) gives a different answer.
if we follow the bytes and the code we see that (&array + 1) actually gives us the memory address four bytes after the end of the array.
so pointer too memory address add one gives the amount of bytes the variable type is past the memory address for the start of the array
and the reference to the pointer too the memory address add one gives the address the amount of bytes the variable type is after the last ?? spot in the array.
how then can array and &array return the same answer if (array + 1) and (&array + 1) do not.
it seems to me that the & reference when working with arrays overloads the + operator when doing arithmatic.
this would explain the difference in answers as straight &array has no operator too overload so returns the same answer as calling for
straight array
this small peice of code also shows that the use of pointers using *(&array + 1) is a very bad way to show a way to find array size with
pointers as really arrays are pointers and *(&array + 1) and (&array + 1) give the same result.
the heavy work was really being done by the reference operator &.
I may still be missing something here as I have used cout directly with the different experssions and being a stream it may
be limited in its ability to take advantage of what the reference operator is really doing when working with arrays.
I am still learning this language but I shall for sure keep this in mind as I dive deaper into c++.
I believe other than a few other trials with variables that the true answer will be found when reading the source for GCC g++.
I am not ready for that yet.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!
...
//initializing first 2D dynamic array
int x=2;
int y=2;
int** array = new int*[x];
for(int i=0; i<x; i++) array[i] = new int[y];
//initializing second 2D dynamic array
int new_x=3;
int new_y=3;
int** temp = new int*[new_x];
for(int i=0; i<new_x; i++) temp[i] = new int[new_y];
//assigning values
array[0][0] = 1;
cout << array[0][0] << endl; //output is 1
//before assigning values to temp[0][0]
cout << temp[0][0] << endl; //out is a huge random number
temp[0][0] = array[0][0];
cout << temp[0][0] << endl; //output is the same huge random number
temp[0][0] = 2;
cout << temp[0][0] << endl; //output is 2
...
Memory under temp[0][0] is allocated dynamically, therefore that's why you're getting some random (garbage) stuff out of it before assigning 2. When you're assigning 2, the random garbage that's been there gets "overwritten" by a meaningful value, in your case 2 of int type
The code snippet you posted works exaclty as it should:
First cout prints 1 witch is the value of array[0][0].
Second cout prints the uninitialized temp[0][0], I compiled it here, and in this case the value is 0, but it could be anything.
Third cout prints 1 due to the assingment temp[0][0] = array[0][0].
Fourth cout prints the value of 2 assigned to temp[0][0].
If there are problems in your code it's not in the posted bit, aside from the fact that you are trying to print an unitialized variable in the second cout
I have tried running the code,and the output indeed is 1 after assigning the value.
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];.
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.
I'm doing work on a multifunction program for my programming class, and one of the functions requires that an array of strings be used.
The objective is to store 10 names in an array, and then have the user enter a number that randomly determines the 'winning' name.
The only problem is that, once I execute my code, the program crashes after completing the 10 loops to get the names. That's the main thing I'm trying to identify, what's causing the crash.
The entire program is much larger, but the relevant code is shown below.
string Name1, Name2, Name3, Name4, Name5, Name6, Name7, Name8, Name9, Name10, tempName, winName;
string array[10] = {Name1, Name2, Name3, Name4, Name5, Name6, Name7, Name8, Name9, Name10};
int tempNum = 0;
int winNum;
int userEntry;
int userSelection;
for (int test = 0; test < 11; test++)
{
cout << "Enter a name: ";
cin >> tempName;
array[tempNum] = tempName;
tempNum++;
}
//The program crashes at this exact spot, right after collecting the 10th name
cout << endl;
cout << "Now choose a random number between 1 and 100: ";
cin >> userEntry;
winNum = static_cast<int>(userEntry * 3.14159 + 12.7 * 10) % 10;
winName = array[winNum];
cout << endl;
cout << "The winner of the game is" << winName << "!" << endl;
In the for loop you are trying to access to array[10] and that does not exist since array has only 10 elements, from 0 to 9. That's why your program is crashing.
Change the condition in your for loop from for (int test = 0; test < 11; test++) to for (int test = 0; test < 10; test++) and it should works.
Your array has 10 elements and and you are accessing 11 elements, 0 to 10, which is causing your program to crash. Because your code is accessing a location which doesn't belong to your program. Change the condition in for loop from test < 11 to test < 10.
Use "at" function of string class if you can, it throws an exception when you try to access out of bound subscripts.
Two problems.
One, you're instantiating an array with 10 elements then looking up its 11th element.
Firstly, change the if condition from test < 11 to test < 10.
This will solve your crash.
Secondly, your program could crash for large inputs.
When you initialize the string array, the compiler assigns a certain amount of memory to the array.
The amount of memory allocated to array is determined by the compiler.
The compiler determines the size of each of the string variables, and multiplies it by 10 to get the total size needed by the array, and allocates that much memory accordingly.
While strings can resize dynamically, arrays do not. The array has a fixed amount of memory allocated to it.
Hence, if during input of the strings that you save into the array by overwriting its indices, you could write into the array more characters than it can hold.
The amount of memory that will be allocated is implementation dependent since the default capacity of a string is implementation dependent.
A simple workaround would be to define the name strings to a large string at the beginning like string Name1 = "-------------------------";
This way the user input is most likely smaller in size that the initial value.