c中的c_str()等价物

 佩政哲维99 发布于 2023-01-02 15:41

我刚刚开始使用C编程语言来编写我的课程项目,而且我对C语言知之甚少.我已经使用C++一段时间了,我需要在C中找到c_str()函数的替代方法.我试图编码(在C中)类似于下面的c ++代码.我完全不知道如何做同样的事情.任何帮助是极大的赞赏.

void putVar(double* var,int N, string name, Engine *ep){
    double row = N, col = N;
    mxArray *matlab = mxCreateDoubleMatrix(row, col, mxREAL);
    double *pa = mxGetPr(matlab);
    memcpy(pa, var, sizeof(double)*row*col);
    engPutVariable(ep, name.c_str() , matlab);
}

ryyker.. 6

我需要在C中找到c_str()函数的替代方法...

如上面的注释中所述,C没有字符串类型,但C确实使用了数组char,而当NULL终止时通常称为C字符串.
在C中创建字符串有很多种方法.以下是三种非常常见的方法:

给出以下内容 :(在此示例中为说明)

#define MAX_AVAIL_LEN sizeof("this is a C string") //sets MAX_AVAIL_LEN == 19

1

char str[]="this is a C string";//will create the variable str, 
                                //populate it with the string literal, 
                                //and append with NULL. 
                                //in this case str has space for 19 char,
                                //'this is a C string' plus a NULL 

2

char str[MAX_AVAIL_LEN]={0};//same as above, will hold 
                      //only MAX_AVAIL_LEN - 1 chars for string
                      //leaving the last space for the NULL (19 total).
                      //first position is initialized with NULL

3

char *str=0;  
str = malloc(MAX_AVAIL_LEN +1);//Creates variable str,
                             //allocates memory sufficient for max available
                             //length for intended use +1 additional
                             //byte to contain NULL (20 total this time)

注意,在该第三例子中,虽然它不伤害,
该"+1"是不是真的有必要如果的最大长度
中使用字符串是<=的长度"这是一个C字符串".
这是因为当在创建MAX_AVAIL_LEN时使用sizeof()时,
它在字符串
文字长度的评估中包含NULL字符.(即19)
尽管如此,在为C字符串分配内存
明确显示在内存分配期间已考虑空字符的空间时,通常以这种方式编写它.

注2,也是第3个例子,必须在使用free(str);完毕后使用str.

在这里寻找更多的C字符串.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有