【问题标题】:C++ `assign()` equivalent in C [closed]C ++ `assign()` 等价于 C [关闭]
【发布时间】:2014-04-15 15:48:42
【问题描述】:

关于如何在 C 中实现 C++ assign() 的任何想法?

C++ 代码示例:

std::string ds;
// snip //
ds.assign((const char *)start, end - start);

在 C 中使用相同的语法在编译时出现以下错误:

error: request for member 'assign' in something not a structure or union

【问题讨论】:

  • 这条语句 ds.assign((const char *)start, end - start);不会在 C++ 中编译。所以我不明白你想要什么。
  • 你说你想实现assign;此代码只是试图使用您已经承认尚未实现的内容。而且,作为 C,字符串不是对象,因此没有方法。
  • @Vlad 来自莫斯科,我确定你错了。
  • @xtmtrx: Vlad 100% 正确。
  • @xtmtrx '没有意识到一个简单的问题会导致投票失败' 嗯,如果被无意识地问到:/ ...

标签: c++ c


【解决方案1】:

您想在 C 中使用 C 字符串,请在 string.h 中查找使用 c 字符串的函数(如 strcpy)

http://www.cplusplus.com/reference/cstring/strcpy/

【讨论】:

  • 谢谢。我认为strcpy 会做到的。
  • 解决参考中给出的示例,还有一些其他的事情,例如您需要设置的内存分配(在示例中,他们只是在堆栈上完成所有操作)。
【解决方案2】:

看来你的意思是下面的代码sn-p

std::string ds;
char s[] = "Hello Wotld";
char *start = s;
char *end = s + sizeof( s ) - 1;

ds.assign( start, end - start );

在 C 中,您处理原始指针。所以类似的东西可能如下所示

char * assign( char *dest, const char *source, size_t n )
{
   free( dest );

   char *p = ( char * )malloc( n + 1 );

   if ( p != NULL )
   {
       strncpy( p, source, n );
       p[n] = '\0';
   }

   dest = p;

   return dest;
}

例如

char *ds = NULL; // it is important to initialize it to NULL
char s[] = "Hello World";

ds = assign( ds, s, sizeof( s ) - 1 );

//...
free( ds );

【讨论】:

  • 是的,我的错,我的意思是std::string ds;
猜你喜欢
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2023-03-09
  • 2020-04-23
  • 1970-01-01
相关资源
最近更新 更多