• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 476
  • Last Modified:

Error: Bad Ptr

Hello Everyone,

I am writing a program that lets a user enter in a equation and then tell if the program encounters an operator.  What I am having a problem with is I am getting a Bad Ptr a run time error from the following pointer tokenPtr. When I debug the error is coming from this line

 if(*tokenPtr == '(' || *tokenPtr == ')' || *tokenPtr == '+' || *tokenPtr=='-')

Also,  the first variable  is in the equation is being skipped by the 'if' evaluation.  

(BTW: There is an expected space between each character)


 
#include<iostream>
#include<string>
#include<cstring>
#include<sstream>
#include<iterator>
#include<vector>
#include<algorithm>

using namespace std;




int main()
{
	
   char equation[20];
   char* tokenPtr;

   cout<<"Please Enter In A Equation"<<endl;

   cin.getline(equation, '\n');
   
   tokenPtr = strtok(equation," ");

   while( tokenPtr != NULL)
   {
	   cout<<tokenPtr<<endl;
	   tokenPtr = strtok(NULL, " ");

	   if(*tokenPtr == '(' || *tokenPtr == ')' || *tokenPtr == '+' || *tokenPtr=='-')
	   {

		   cout<<"This Is A Operator"<<endl;
	   }
   }


	
	system("PAUSE");

	return 0;
}

Open in new window

0
brich744
Asked:
brich744
  • 2
1 Solution
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You are calling strtok (the one inside the loop) but not checking the return value.

I'm not 100% sure of what your logic should be, but either check for a null ptr in the if statement, ie.

  if(tokenPtr != NULL && (*tokenPtr == '(' || *tokenPtr == ')' || *tokenPtr == '+' || *tokenPtr=='-'))

or move the strtok call on line 29 down below the if statement
0
 
sarabandeCommented:
simply move the strtok call in line 29 to end of loop.

Sara
0
 
sarabandeCommented:
mccarl, sorry for repeating.

Sara
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now