检查字符串是否可以在 C 中改变
Check if string can be mutated in C
假设我有这个功能:
void f(char *s) {
s[0] = 'x';
}
这个函数有时会出错,有时不会。例如,
char *s = "test";
f(s); // Error
char t[] = "test";
f(t); // Success
函数f
里面,是否可以先判断s[0] = 'x';
会不会报错?
鉴于我收到的反馈,听起来我应该改为记录函数是否要求其参数可变。例如:
#include <stdio.h>
#include <string.h>
char* f(char*);
void g(char*);
int main(int argc, char *argv[]) {
// s is immutable.
char *s = "test";
puts(f(s));
// t is mutable.
char t[] = "test";
g(t);
puts(t);
}
/*
* Returns a copy of the given string where the first character is replaced with 'x'.
* Parameter s must contain at least one character.
*/
char* f(char *s) {
char *t = strdup(s);
t[0] = 'x';
return t;
}
/*
* Replaces the first character of the given sting with 'x'.
* Parameter s must contain at least one character and be mutable.
*/
void g(char *s) {
s[0] = 'x';
}
调用者有责任遵守参数可变的函数要求,而不是相反。
const char *s = "test"; // tell compiler s is immutable
f(s); // compilation error since f() requires a non-const argument
char t[] = "test";
f(t); // Success
阻止编译器在上面拒绝 f(s) 的唯一方法是从 s 的声明中删除 const,或者放弃 const'ness。除了极少数情况外,两者都是问题的积极指标。
注意:在没有 const 限定符的情况下声明 s 是语言中的一个异常现象。练习在需要时使用 const(例如,在使用字符串文字初始化指针时)。这样就消除了很多程序错误。
假设我有这个功能:
void f(char *s) {
s[0] = 'x';
}
这个函数有时会出错,有时不会。例如,
char *s = "test";
f(s); // Error
char t[] = "test";
f(t); // Success
函数f
里面,是否可以先判断s[0] = 'x';
会不会报错?
鉴于我收到的反馈,听起来我应该改为记录函数是否要求其参数可变。例如:
#include <stdio.h>
#include <string.h>
char* f(char*);
void g(char*);
int main(int argc, char *argv[]) {
// s is immutable.
char *s = "test";
puts(f(s));
// t is mutable.
char t[] = "test";
g(t);
puts(t);
}
/*
* Returns a copy of the given string where the first character is replaced with 'x'.
* Parameter s must contain at least one character.
*/
char* f(char *s) {
char *t = strdup(s);
t[0] = 'x';
return t;
}
/*
* Replaces the first character of the given sting with 'x'.
* Parameter s must contain at least one character and be mutable.
*/
void g(char *s) {
s[0] = 'x';
}
调用者有责任遵守参数可变的函数要求,而不是相反。
const char *s = "test"; // tell compiler s is immutable
f(s); // compilation error since f() requires a non-const argument
char t[] = "test";
f(t); // Success
阻止编译器在上面拒绝 f(s) 的唯一方法是从 s 的声明中删除 const,或者放弃 const'ness。除了极少数情况外,两者都是问题的积极指标。
注意:在没有 const 限定符的情况下声明 s 是语言中的一个异常现象。练习在需要时使用 const(例如,在使用字符串文字初始化指针时)。这样就消除了很多程序错误。