我是C的初学者,我相对无能为力,所以我希望有人可以提供帮助。
我有一个方法,它根据某个数字返回一个字符串。
char* getStr(int aNumber)
{
char *str= malloc(15);
if(!str)
return NULL;
if(aNumber == 0)
str = "this";
else if(aNumber== 1)
str = "that";
// other "else if" statements
else
str= "nope";
return str;
}
我用另一种方法:
char *myString = getStr(number1);
printf("%s", myString);
char *myOtherString = getStr(number2)
printf("%s", myOtherString);
我现在的问题是myOtherString与myString相同。在getStr()方法中使用strdup()而不是malloc()也有同样的效果,同时放弃两者并且只是尝试返回str而不会导致随机符号打印出来(diamons和问号)。
如何更改getStr()方法以允许输出字符串在每次调用方法时都不同?或者在以其他方法调用后,我是否必须以某种方式释放分配给字符串的空间?
答案 0 :(得分:2)
也许你想要的是:
char* getStr(int aNumber)
{
char *str= malloc(15);
if(!str)
return NULL;
if(aNumber == 0)
strcpy(str,"this");
else if(aNumber== 1)
strcpy(str, "that");
// other "else if" statements
else
strcpy(str, "nope");
return str;
}
不是吗?
答案 1 :(得分:0)
C字符串不是基本类型。它们是角色的指针。
也许您的功能的注释版本会有所帮助。
char* getStr(int aNumber)
{
/* make str point to a new block of uninitialized memory */
char *str= malloc(15);
if(!str)
return NULL;
/* make str point to some other constant array, do not free original allocation */
if(aNumber == 0)
str = "this";
else if(aNumber== 1)
str = "that";
// other "else if" statements
else
str= "nope";
return reg;
}
答案 2 :(得分:0)
您可以使用以下内容:
#define STRLEN 15
char* getStr(int aNumber)
{
char *str= malloc(STRLEN);
if(!str)
return NULL;
if(aNumber == 0)
snprintf(str, STRLEN, "this");
else if(aNumber== 1)
str = snprintf(str, STRLEN, "that");
// other "else if" statements
else
snprintf(str, STRLEN, "nope");
return str;
}
答案 3 :(得分:0)
我认为我是否应该简单地返回文字的地址。
char* getStr(int aNumber){
if(aNumber == 0)
return "this";
else if(aNumber == 1)
return "that";
return "nope";
}
转动const char*
以强调无法更改返回值。
如果要更改已返回的字符串,
在这种情况下,您必须被释放,调用者必须复制strcpy
组才能使用malloc
保护的区域。
但可能你不会改变字符串。