Home >Backend Development >C++ >How to solve C++ syntax error: 'expected primary-expression before '*' token'?
How to solve C syntax error: 'expected primary-expression before '*' token'
In the process of learning C programming, we often encounter various syntaxes mistake. One of the common errors is 'expected primary-expression before '*' token'. This error usually occurs when using pointers, mainly because we use wrong syntax somewhere or forget to use the correct syntax. Some common error causes and solutions are introduced below.
int *ptr; // 正确的声明指针变量 *ptr = 5; // 错误的使用指针
The workaround is to declare the pointer variable before using it, like this:
int *ptr; // 声明指针变量 ptr = new int; // 分配内存 *ptr = 5; // 使用指针 delete ptr; // 释放内存
int *ptr = new int; *ptr = 5; // 正确的使用指针 int* ptr = new int; * ptr = 5; // 错误的使用指针,星号的位置错误
The solution is to put the asterisk after the variable name, like this:
int *ptr = new int; *ptr = 5; // 正确的使用指针
int *ptr = new int *ptr = 5;
The solution is to check for other syntax errors in the code and fix them as follows:
int *ptr = new int; *ptr = 5;
When solving syntax errors, we should be careful Examine the code and understand the features and rules of C syntax. We can also use an IDE (Integrated Development Environment) to help us find and solve syntax errors. IDEs usually give tips and suggestions when we enter code to help us avoid some common mistakes.
To sum up, when we encounter the C syntax error: 'expected primary-expression before '*' token', we should first check whether we forgot to declare the pointer variable, whether the asterisk position is correct, and other syntax errors. exist. By carefully checking and correcting the code, we can successfully resolve this error and proceed with C programming smoothly.
The above is the detailed content of How to solve C++ syntax error: 'expected primary-expression before '*' token'?. For more information, please follow other related articles on the PHP Chinese website!