Strangeness with dynamic arrays in C++ [closed] - c++

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 8 years ago.
Improve this question
I am honestly not quite sure what is going on here.
It has been years since I have programmed in C++, but I am trying to execute this code
short* result = new short[3];
now, I would expect that this creates an array with 3 memory locations: 0,1 and 2, but for what ever reason, this works:
result[0] = someObject::parseShort();
but this does not work:
result[1] = someObject::parseShort();
no exception is thrown, but it is like addresses 1 and 2 dont even exist? I have verified this with visual studio's debugger, and this is leading to some very interesting results when I try to read from those memory addresses, no matter what I Initially wrote to them, they always seem to return 0
Like I said, its been years since I've written anything in C++, and would appreciate someone being able to tel me what is going on? because as far as I can tell, it looks like I am defining the array right?
EDIT:
here is the rest of the relevent code:
phoneNumber::phoneNumber(string number)
{
short* nbrs = parseNumber(number);
areaCode = nbrs[0];
prefix = nbrs[1];
this->number = nbrs[2];
delete[] nbrs;
}
areaCode, prefix, and number are all members of the class.
area code gets set correctly, but prefix and number dont seem to
here is the definition of parseNumber:
short* phoneNumber::parseNumber(string num)
{
if (num == "")
throw new exception("value should not be null");
int var= 3;
short* result= new short[var];
string temp = "";
bool fail = false;
int j = 0;
bool ready = false;
num = Utils::removeSpaces(num);
if (j ==0&&num[0] != '(')
{
fail = true;
}
for (int i = 1; i < num.length(); i++)
{
if (fail)
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
if (num[i] >= '0' && num[i] <= '9')
{
temp+=num[i];
continue;
}
else if (j== 0 && num[i] ==')')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if(j==1 && num[i] =='-')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if (j == 3 && i == num.length() -1)
{
if(temp.length() != 4)
{
fail = true;
continue;
}
ready = true;
}
else
{
fail = true;
continue;
}
if (ready)
{
result[j]= Utils::parseShort(temp);
j++;
temp = "";
ready = false;
continue;
}else
{
temp+= num[i];
}
}
if (temp.length()==4)
result[j]= Utils::parseShort(temp);
else
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
return result;
}

Yes, you are defining your array right. You have a bug elsewhere in your code outside the part that constitutes your question.

Related

guessing game, (While loop, if statement ), play again prompt not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
So I'm really new to java and I was trying to practice using while and if statements through a guessing game app.
Everything seemed to work until I'm promped to play again. When I type Y, the loop ends. This isn't supposed to happen as the while argument at the beginning of the code says to keepPlaying if true.
I've tried playing with the argument to make it: while (answer == "Y"). I've played around with it but it always keeps exiting. Please help!!
Here's the code:
import java.util.Scanner;
public class GuessingGame
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
// TODO Auto-generated method stub
String answer = "Y";
int guess;
int number;
String again;
boolean keepPlaying = true;
System.out.println("Let's play a guessing game!");
while (keepPlaying)
{
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = sc.nextInt();
while (guess > 10 || guess < 1)
{
System.out.print("I said, between 1 and 10. Try again: ");
guess = sc.nextInt();
}
number = (int)(Math.random() *10 + 1);
if (guess == number)
{
System.out.println("You're right!");
}
else
{
System.out.println("You're wrong! the number was " + number);
}
System.out.print("Play again? (Y or N)");
answer = sc.next();
if (answer == "Y")
{
keepPlaying = true;
}
else
{
break;
}
}
System.out.println("Thank you for playing");
}
}
In the comparison, you should compare using the String requirements:
if (answer.equals("Y")) // NOTE: I'd use .equalsIgnoreCase(...)
{
keepPlaying = true;
}
else
{
break;
}
Also note that since this comparison is at the end of the loop, you could simplify to:
keepPlaying = answer.equalsIgnoreCase("Y");
As you do not need the break statement since the loop will be re-evaluated.

Can't figure out how to loop playerturns and moves Tic Tac Toe (C++) [closed]

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 6 years ago.
Improve this question
EDIT: Solved now thank you triple_r and AJNeufield for your help on this problem I was having.
I've looked around multiple websites and YouTube about this and I can't seem to find anything on what I am specifically looking for this as my format for the program is a good bit different than others. Therefore, it's hard to decipher where I need to put the things I do need that I know of.
Please note that I'm relatively new to C++ so I'd appreciate all the feedback or criticism you might provide me.
Also, note my code does compile and run it just does not allow me to put in more than one input and more than likely does not allow for a switch of player turns.
Quick Edit: Switched the code with the new setup suggested by triple_r but I seemed to have messed it up somewhere along the line and it does compile(with the exception of x and y not being utilized and one other error) but it always starts off with player 2 going first and as soon as it receives input it ends automatically with a segmentation fault.
#include <iostream>
#include <cstdlib>
using namespace std;
//////////////////////////////////////////////////////////
void initboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
for (y=0;y<3;y++)
board[x][y]=' ';
return;
}
//////////////////////////////////////////////////////////
void printboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
{
cout<<"\n";
for (y=0;y<3;y++)
{
cout<<" "<<board[x][y]<<" ";
if (y<2) cout<<"|";
}
if (x<2) cout<<"\n===========";
}
return;
}
//////////////////////////////////////////////////////////
void getmove(char board[3][3], int player)
{
return;
}
//////////////////////////////////////////////////////////
int main()
{
bool done=false;
char board[3][3];
int x,y,player=1,turn,playerchoice,playermark;
initboard(board);
turn=0;
do
{
if (player==1)
playermark='X';
else
playermark='O';
if (turn%2)
player=1;
else
player=2;
cout<<"Player "<<player<<" where do you want to move?: ";
cin>>playerchoice;
if (playerchoice==1)
{
board[0][0]=playermark;
}
else if (playerchoice==2)
{
board[0][1]=playermark;
}
else if (playerchoice==3)
{
board[0][2]=playermark;
}
else if (playerchoice==4)
{
board[1][0]=playermark;
}
else if (playerchoice==5)
{
board[1][1]=playermark;
}
else if (playerchoice==6)
{
board[1][2]=playermark;
}
else if (playerchoice==7)
{
board[2][0]=playermark;
}
else if (playerchoice==8)
{
board[2][1]=playermark;
}
else if (playerchoice==9)
{
board[2][2]=playermark;
}
else
{
cout<<"Invalid move ";
}
if (board[x][y]!=' ')
cout<<"Move is already taken.";
board[x][y]=playermark;
if(board[x][y]==' ')
turn++;
}while (!done);
void printboard(char board[3][3]);
return 0;
}
EDIT: based on the updated code
So, the first thing I can see is that you are using x and y in your program but you don't initialize them or assign any values to them. Also, try to use functions/classes/... yo make your code more readable. You already have a function for player move but you are not using it. You can move the large if statement inside that function and that will make your main code shorter and more readable.
Here are my comments on the main part of your program:
int main()
{
// add a new variable to see if the move was valid or not:
bool done=false, validmove = true;
char board[3][3];
int x, y, player = 1, turn = 0, playerchoice, playermark;
initboard(board);
do
{
// swap the two `if`s so you decide who`s turn it is then assign the player mark,
// also, reverse the condition to make sure turn '0' is player 1's turn.
if (!(turn % 2))
player = 1;
else
player = 2;
if (player == 1)
playermark = 'X';
else
playermark = 'O';
cout << "Player " << player << " where do you want to move?: ";
cin >> playerchoice;
// Assign `x` and `y` here instead of updating the board, because you want to make
// sure that the move is valid before putting the mark:
validmove = true;
if (playerchoice == 1)
{
x = 0; y = 0;
}
else if (playerchoice == 2)
{
x = 0; y = 1;
}
else if (playerchoice == 3)
{
x = 0; y = 2;
}
else if (playerchoice == 4)
{
x = 1; y = 0;
}
else if (playerchoice == 5)
{
x = 1; y = 1;
}
else if (playerchoice == 6)
{
x = 1; y = 2;
}
else if (playerchoice == 7)
{
x = 2; y = 0;
}
else if (playerchoice == 8)
{
x = 2; y = 1;
}
else if (playerchoice == 9)
{
x = 2; y = 2;
}
else
{
cout << "Invalid move, try again!";
// Make sure to mark the move as invalid so they get a chance to
// change their move:
validmove = false;
}
// check to see if the turn was valid:
if(validmove)
{
if (board[x][y] != ' ')
{
cout << "Move is already taken, try again";
}
else
{
board[x][y] = playermark;
turn++;
}
}
// have to make sure you have a condition for end of game. A simple
// one is to check if turn is less than `9`, otherwise the board is
// full:
if(turn == 9)
done = true;
// you probably want to add a few more checks to see who won the game.
}while (!done);
// when calling a function, no need to put the return type or parameter type:
printboard(board);
return 0;
}
========================================================================
There are two do-while loops in your program and both seem to be meant as a game loop. What I would do is:
initboard(...);
turn = 0;
do{
//this is the game loop
...;
if( validturn )
turn++;
}while(!done);
release_resources(...);
return 0;
so, you fold everything into one loop. In that loop, you want to:
find who's turn it is:
if (turn % 2)
player = 1;
else
player = 2;
get users input:
std::cin >> playerchoice;
...
convert player choice to grid location:
switch ( move )
{
case 0:
x = 0;
y = 0;
break;
case 1:
...;
...
default:
//invalid move
}
see if the move is valid:
if( board[x][y] != ' ' )
//already taken, invalid move
then apply the move:
board[x][y] = playermark;
I hope this helps.
Your cin >> playerchoice is outside your do { ... } while ( moves != 9); loop. Move it inside.

Arrays giving me errors:: String subscript out of range; but everything seems to be in order

I've run into some problems with arrays, one while I was coding in Winsock and one in DirectX 11. In DirectX 11 its actually a texture array that I'm trying to release.
Here's the Winsock problem:
int retval;
retval = recv(hclientSocket, tempBuffer, sizeof(tempBuffer), 0);
if (retval == 0)
{
break; // Connection has been closed
}
else if (retval == SOCKET_ERROR)
{
throw ErrorHandler("Failed to receive due to socket");
}
else
{
Encyrption enc;
string done = enc.Cipher(tempBuffer, retval);
retval = retval * 3;
cout << retval; // it prints out 3
for (int i = 0; i < retval; i++) {
tempBuffer[i] = done[i]; //the error is being pointed here on the 6th time it runs through this, even though its only suppose to go through this 3 times
}
if (send(hclientSocket, tempBuffer, retval, 0) == SOCKET_ERROR)
throw ErrorHandler("Failed to send due to socket");
}
okay most of this code I got from a Winsock tutorial place, but I wanted to try a different encryption method.
Here's the call function, because originally intended to pass and return a string but this time I'm passing a char* and returning a string, which is converted in the above code.
The encryption takes in one character and turns it into a string of 3 for example a would become bca and c would become cba or something that's why I'm multiplying retval by 3. It prints out everything I want it to print out, but its giving an error after its done.
string pass = (string)message;
pass.resize(size);
for (int i = 0; i < size; i++) {
if (!isalnum(pass[i])) {
return "\n";
}
else {
return Cipher(pass);
}
}
Okay so here's the Directx11 problem
I recently learned how to use multitextures utilizing a texture array, and Im having trouble releasing it.
#define TEXTURE_ELEMENTS_COUNT 2
ID3D11ShaderResourceView* m_textures[TEXTURE_ELEMENTS_COUNT];
for (int i = 0; i <= TEXTURE_ELEMENTS_COUNT; i++) {
m_textures[i] = 0;
}
//some code here
for (int i = 1; i <= (TEXTURE_ELEMENTS_COUNT - 1); i++) {
m_textures[i]->Release(); //it throws an exception right here, but I can't figure out why, I tried change `i` to zero, but it still throws it.
m_textures[i] = 0;
}
Thanks for taking the time to look through my code, I have no idea what I'm doing wrong and arrays sometimes throw me off, because its suppose to start at zero and sometimes its hard for me to visualize. Anyway thanks for any input in advance.
Your element count is 2. Therefore you have an element at position 0 and at position 1.
So you have to start your loop at "i = 0" and end your loop after "i = 1". So start from 0 and run to "i < maxCount".
for (int i = 0; i < TEXTURE_ELEMENTS_COUNT; i++) { //FROM 0 TO i<MAXCOUNT
m_textures[i] = 0; // HERE YOU CREATE A NULLPTR TO EVERY SRV
}
//some code here
for (int i = 0; i < (TEXTURE_ELEMENTS_COUNT); i++) { //USE THE SAME LOOP
m_textures[i]->Release(); //IF THERE IS ALREADY A NULLPTR YOU HAVE AN INVALID ACCESS
m_textures[i] = 0;
}
Try to use the Safe_Release function if you use the SDK. Otherwise define it for yourself.
SAFE_RELEASE(m_textures[i])
There is an included test for nullptr:
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(x)
if(x != NULL)
{
x->Release();
x = NULL;
}
#endif
Good Luck

Error: not all control paths return a value

I am writing two functions in a program to check if a string has an assigned numeric code to its structure array or if the given numeric code has an assigned string in the same structure array. Basically, if I only know one of the two, I can get the other. I wrote the following:
int PrimaryIndex::check_title_pos(std::string title) {
bool findPos = true;
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
} else {
return -1;
}
}
std::string PrimaryIndex::check_title_at_pos(int pos) {
bool findTitle = true;
if (findTitle) {
for (int p = 1; p <= 25; p++) {
if (my_list[p].tag == pos) {
return my_list[p].title;
}
}
} else {
return "No title retrievable from " + pos;
}
}
However, it says not all control paths have a return value. I thought the else {} statement would handle that but it's not. Likewise, I added default "return -1;" and "return "";" to the appropriate functions handling int and string, respectively. That just caused it to error out.
Any idea on how I can keep this code, as I'd like to think it works but cant test it, while giving my compiler happiness? I realize through other searches that it sees conditions that could otherwise end in no returning values but theoretically, if I am right, it should work fine. :|
Thanks
In the below snippet, if s iterates to 26 without the inner if ever evaluating to true then a return statement is never reached.
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
}

I keep getting this Debug Assertion Failed? Expression: list iterator not dereferenceable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm getting an assertion failure "list iterator not dereferencable" from the following code:
It says that it is from the last line.
void cpuschedule::Sjf()
{
int CT = 0;
bool IO = false;
Data temp;
for(it = lPro.begin(); it != lPro.end(); ++it)
{
if(it->RQ)
{
temp.AT = it->AT;
temp.BUT = it->BUT;
temp.BUP = it->BUP;
temp.IOP = it->IOP;
temp.IOT = it->IOT;
temp.ProNum = it->ProNum;
temp.RQ = it->RQ;
temp.vData = it->vData;
Ready.push_back(temp);
}
}
it2 = Ready.begin();
while(!(Ready.empty()))
{
if(IO)
{
for(iR = Ready.begin(); iR != Ready.end(); ++iR)
{
if(!(iR->RQ))
{
(iR->IOT)--;
if(iR->IOT == 0)
{
iR->BUP += 2;
iR->IOP += 2;
iR->BUT = iR->vData[(iR->BUP)];
iR->IOT = iR->vData[(iR->IOP)];
iR->RQ = true;
iR->AT = CT;
}
if(iR->IOT == -121)//Check for the end of the Vector
{
temp.AT = iR->AT;
temp.BUT = iR->BUT;
temp.BUP = iR->BUP;
temp.IOP = iR->IOP;
temp.IOT = iR->IOT;
temp.ProNum = iR->ProNum;
temp.RQ = iR->RQ;
temp.vData = iR->vData;
Out.push_back(temp);//Instert to the List of Done
iR = Ready.erase(iR);
}
}
}
}
Ready.sort(comp);
if((it2->BUT != 0) && (it2->RQ))
{
it2->BUT--;
if(it2->BUT == 0)
{
printState(CT);
it2->RQ = false;
IO = true;
if(next(it2) == Ready.end())
{
it2 = Ready.begin();
}
else
++it2;
}
}
CT++;
}
}
This is a while loop for a CPU Scheduling SJF.
It goes up to 691 and it should do 901 loops
Your loop performs iR = Ready.erase(iR); and then does iR++ anyway. This is wrong, if the element erased was the last one; you go one-over-the-end.
The common idiom is:
for ( ; iR != end; ) { // <-- NO iR++
if (condition_to_erase)
iR = Ready.erase(iR);
else
iR++;
}