取消引用导致错误:")"标记之前的预期主表达式

Dereference causes error: expected primary-expression before ')' token

本文关键字:表达式 引用 错误 取消      更新时间:2023-10-16

当我在函数中使用解引用作为参数时,预处理器会吐出一个错误。我相信括号前的*会引起编译器的歧义。有什么办法可以绕过这个吗?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main ()
{
  char *in = NULL;
  char *out = NULL;
  getline(cin,in*);//error
  out=system(in*);//error
  printf(out);
  return 0;
} 

错误在标记的行上。谢谢你!

解除对in的引用写成*in,而不是in*。(此外,即使修复了这个问题,您的程序仍然无法工作,因为您试图解引用NULL,并且getline的第二个参数将具有错误的类型。char*字符串不像你想象的那样工作

getline只适用于c++字符串(不是C风格的字符串)。c++字符串可以根据读取的数据量分配内存。

还有其他的函数可以读取C字符串,但是你必须预先分配你想要的内存量,并指定你已经分配了多少内存量。一般来说,没有理由这样做,因为c++字符串版本更简单,更不容易出错。

同时,避免包含c风格的标准头(即以.h结尾)并避免使用指针。system返回int类型,而不是string类型。

的例子:

#include <iostream>    // cin, cout
#include <string>      // string
#include <cstdlib>     // system
int main()
{
    std::string s;
    std::getline( std::cin, s );
    int system_result = std::system( s.c_str() );
    std::cout << system_result << "n";
}