【问题标题】:Value of type char* cannot be used to initialize an entity of type "char"char* 类型的值不能用于初始化“char”类型的实体
【发布时间】:2014-06-17 00:40:19
【问题描述】:

我是 C++ 新手,我想做一些简单的事情,例如将 char[] 的内容写入磁盘

我很难做到。

这是我的代码:

char x[256],y[256],z[256];

        sprintf( x, "%.2f", pCommandHandling->m_dtHandleInformation[i].Xfrms.translation.x ); //pCommandHandling->m_dtHandleInformation[i].Xfrms.translation.x  is a float struct


        sprintf( y, "%.2f", pCommandHandling->m_dtHandleInformation[i].Xfrms.translation.y ); //pCommandHandling->m_dtHandleInformation[i].Xfrms.translation.y  is a float struct


        sprintf( z, "%.2f", pCommandHandling->m_dtHandleInformation[i].Xfrms.translation.z ); //pCommandHandling->m_dtHandleInformation[i].Xfrms.translation.z  is a float struct

    FILE *tracker_file = fopen("NDI_FiMe.TMP","w");
                char buffer[] = {x,";",y,";",z};
                fwrite(buffer , sizeof(char), sizeof(buffer), tracker_file);
                fclose(tracker_file);

我遇到的问题是:

IntelliSense:“char *”类型的值不能用于初始化“char”类型的实体

【问题讨论】:

  • 你想让char buffer[] = {x}做什么?复制数组?
  • 好吧,让我修改我的示例以添加更多代码,不仅仅是x,还有3个变量。 x、y 和 z
  • 让你的例子成为一个真正给你错误的真实程序。 stackoverflow.com/help/mcve

标签: c++ char initialization entity


【解决方案1】:

您不能将字符数组 (x) 放入字符列表中。正如错误消息所说。如果您想将一个 char 数组复制到另一个 char 数组中,请参阅 strcat 系列函数。

下一个错误涉及 sizeof。它不计算字符串的长度。当您现在使用它时,它将给出 4:缓冲区指针的大小。有一个 strlen 函数用于获取 C 字符串的长度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 2019-08-25
    • 1970-01-01
    • 2020-05-27
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多