应用函数时 char* 变化
char* change when applying a function
我正在尝试实现一个将 [name]
形式的 char*
转换为 name
的函数。
这是我的功能:
char* rmChar (char* tagName){
char* newName = tagName;
newName++; //remove first character
unsigned long len = strlen(newName)-1;
if (newName[len] == '\n'){
newName[len] = 0;
newName[len-1] = 0;
}
else{
newName[len] = 0;
}
return newName;
}
我不明白的是,如果我将我的函数应用于 char*
类型的变量,它会修改它。
例如,如果我 运行 以下代码:
char test[] = "[test]";
printf("%s", rmChar(test));
printf("%s", test);
然后打印出来:test[test
我不明白为什么变量变成了[test
?
有没有办法修改我的函数 rmChar,使变量 test
不变?
谢谢!
通过 char*
,您传递的是字符串所在的位置,而不是字符串本身。
因此,修改字符串也会修改原来的字符串。
为避免这种情况,您可以在修改之前复制字符串。
示例修复:
#include <stdlib.h> /* for using malloc() and free() */
char* rmChar (char* tagName){
/* copy input string */
static char* copiedStr = NULL;
free(copiedStr);
copiedStr = malloc(strlen(tagName)+1);
strcpy(copiedStr, tagName);
/* and edit it */
char* newName = copiedStr;
newName++; //remove first character
unsigned long len = strlen(newName)-1;
if (newName[len] == '\n'){
newName[len] = 0;
newName[len-1] = 0;
}
else{
newName[len] = 0;
}
return newName;
}
此函数允许像 printf("%s", rmChar(test));
一样丢弃返回的指针
内存泄漏最少,但在多线程使用时不安全。
我正在尝试实现一个将 [name]
形式的 char*
转换为 name
的函数。
这是我的功能:
char* rmChar (char* tagName){
char* newName = tagName;
newName++; //remove first character
unsigned long len = strlen(newName)-1;
if (newName[len] == '\n'){
newName[len] = 0;
newName[len-1] = 0;
}
else{
newName[len] = 0;
}
return newName;
}
我不明白的是,如果我将我的函数应用于 char*
类型的变量,它会修改它。
例如,如果我 运行 以下代码:
char test[] = "[test]";
printf("%s", rmChar(test));
printf("%s", test);
然后打印出来:test[test
我不明白为什么变量变成了[test
?
有没有办法修改我的函数 rmChar,使变量 test
不变?
谢谢!
通过 char*
,您传递的是字符串所在的位置,而不是字符串本身。
因此,修改字符串也会修改原来的字符串。
为避免这种情况,您可以在修改之前复制字符串。
示例修复:
#include <stdlib.h> /* for using malloc() and free() */
char* rmChar (char* tagName){
/* copy input string */
static char* copiedStr = NULL;
free(copiedStr);
copiedStr = malloc(strlen(tagName)+1);
strcpy(copiedStr, tagName);
/* and edit it */
char* newName = copiedStr;
newName++; //remove first character
unsigned long len = strlen(newName)-1;
if (newName[len] == '\n'){
newName[len] = 0;
newName[len-1] = 0;
}
else{
newName[len] = 0;
}
return newName;
}
此函数允许像 printf("%s", rmChar(test));
一样丢弃返回的指针
内存泄漏最少,但在多线程使用时不安全。