我试图将字符串转换为大写,例如转换test.pdf为TEST.PDF.但是,当我尝试使用打印返回值时printf,它会打印一些垃圾值.我究竟做错了什么?
char *covertToUpper(char *str)
{
int i = 0;
int len = 0;
len = strlen(str);
char newstr[len+1];
for(i = 0; str[i]; i++)
{
newstr[i] = toupper(str[i]);
}
//terminate string
newstr[i]= '\0';
return newstr;
}
Run Code Online (Sandbox Code Playgroud)
Per*_*rry 11
你得到垃圾的原因是因为你在newstr堆栈上分配然后返回它的值.这是C中的一个大禁忌.你之后调用的每个函数,包括printf()函数本身,都会践踏你的所有内容分配.
不幸的是,C有点危险.它不会阻止您将在堆栈上分配的字符串返回给调用函数,即使该函数在返回时声明的函数不再安全使用.
不是以这种方式分配字符串,而是需要在堆上为它分配新的内存,使用malloc()或calloc()设置newstr为指向它.例如,您可以声明:
char newstr = malloc(len);
Run Code Online (Sandbox Code Playgroud)
free()当然,当它不再使用时,需要适当地进行.
BLU*_*IXY 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *covertToUpper(char *str){
char *newstr, *p;
p = newstr = strdup(str);
while(*p++=toupper(*p));
return newstr;
}
int main (void){
char *str = "test.pdf";
char *upstr;
printf("%s\n", str);
upstr=covertToUpper(str);
printf("%s\n", upstr);
free(upstr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62939 次 |
| 最近记录: |