c中有问题,字符串createLabel()功能出错 [英] there is some problem in c and error on string createLabel() fuction
本文介绍了c中有问题,字符串createLabel()功能出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <string.h>
#include <stdlib.h> // for itoa() call
#include <stdio.h>
static int labelCount = 0;
void main()
{
string Label = createLabel();
printf("%s\n", Label);
}
string createLabel()
{
string buf = "";
string lbl = "L";
labelCount++;
// Convert int to string [buf]
itoa(labelCount, buf, 10);
strcat(lbl, buf);
return lbl;
}
推荐答案
不,那只是您对文档的阅读(以及c/c ++代码的混合)
您不能在这些函数中使用string
数据类型.这些函数旨在与C样式的以null终止的字符串(字符数组,以NULL终止)一起使用.
在这里''去:
Nah, it''s just your reading of the documentation (and mixing of c/c++ code)
You can''t use thestring
datatype with these functions. These functions are designed to work with C-style null-terminated strings (arrays of chars, terminated with a NULL)
Here ''go:
#include <string.h>
#include <stdlib.h> // for itoa() call
#include <stdio.h>
static int labelCount = 0;
char *createLabel()
{
char buffer[16];
char *result;
labelCount++;
sprintf(buffer, "L%d", labelCount);
result = strdup(buffer);
return result;
}
int main()
{
char *Label;
Label = createLabel();
printf("%s\n", Label);
free(Label); // free memory allocated in call to strdup
return 0;
}
这篇关于c中有问题,字符串createLabel()功能出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文