大写的字符串,返回局部变量 [英] Capitalize string and return local variable

查看:124
本文介绍了大写的字符串,返回局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使该将利用一个字符串的方法,但我得到的垃圾值,并从我返回一个局部变量的地址,海湾合作委员会的警告。从Python的到来,我对这个问题感到困惑。 (不想用的东西<&string.h中GT;

I'm trying to make a procedure that will capitalize a string, but I get junk values and a warning from gcc that I'm returning the address of a local variable. Coming from Python, I'm confused by this issue. (Don't want to use stuff in <string.h>)

 2
 3
 4char* strcaps(const char *strlower)
 5{
 6  int len = 0;
 7  while (*strlower != '\0'){
 8    len++;
 9    strlower++;
10  }
11  char newStr[len + 1];
12  int i;
13  for (i = 0; i < len; i++)
14    newStr[i] = strlower[i] - 32;
    newStr[len + 1] = '\0';    //EDIT, just put this in.
15  return newStr;
16}
17
18int main(void)
19{
20  
21  
22  
23  printf("I expect capitalized version of edgar, I got %s\n", strcaps("edgar"));
24
25
26  return 0;
27}

我猜我可以做一个全球性的字符串,然后可变的,但我宁愿保留一切功能strcaps里面......这是当我应该使用malloc案件?

I'm guessing I can make a global string and then mutable that, but I'd rather keep everything inside the function strcaps...is this a case when I should use malloc?

感谢

编辑:刚刚意识到,我从来没有把'\\ 0 在新的字符串的结尾,虽然我不知道这是相关的。

Just realized that I never put a '\0' at the end of the new string, although I'm not sure if that is related.

推荐答案

您必须用C两个选项。

1)您可以将指针传递你的函数的字符串和功能将修改并返回void

1) you can pass your function an pointer to the string and function will modify it and return void

在这种情况下,你可以使用原始字符串

In this case you can just use the original string

2)你可以通过你的函数为const char * 并返回的char * ,但你需要对malloc在函数内部

2) you can pass your function const char* and return char *, but then you need to malloc inside the function

如果你做内部功能的malloc,然后你可以使用字符串(打印或做任何你想要的),在和调用程序的免费

If you do a malloc inside function, you can then use the string (print it or do whatever you want), at the and of the program you call free

这篇关于大写的字符串,返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆