• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 478
  • 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)


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)
	   tokenPtr = strtok(NULL, " ");

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

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


	return 0;

Open in new window

  • 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
simply move the strtok call in line 29 to end of loop.

mccarl, sorry for repeating.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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