对于以下question ,
<小时/>Write a function
replace
which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced.Thus
char *cat = "The cat sat"; n = replace( cat );
should set
cat to "The-cat-sat"
and
n to 2.
在上面的问题中,char *cat="That cat sat"
只不过是const char *cat="That cat sat"
这是我针对此问题的非工作代码,
#include<stdio.h>
int replace(char[]);
int main(void){
const char *cat = "The cat sat";
int n = replace((char[])cat);
printf("\n Now the output is: \"%s\"", cat);
printf("n is %d", n);
}
int replace(char cat[]){
int count =0;
for(int i =0; cat[i] != '\0'; i++){
if(cat[i] == ' ') {
cat[i] = '-';
count++;
}
}
return count;
}
<小时/>
要分析此代码,
const char *cat
指向一个无法修改的缓冲区(The cat sat
)。
因此,在调用 replace((char[ ])猫)
。因为,C 是松散类型的
但是程序仍然在cat[i]='-'
如何理解这个问题?
最佳答案
我在这个问题中详细讨论了这个问题:
Difference between declared string and allocated string .
简而言之,声明字符串的方式,无论const
存储类修饰符如何,都存储在RODATA(即:文本段)中,因此重新-将其转换为非 const(您应该尽量避免,因为这样做的合法理由很少)对您没有帮助。
在 c ,如果您想使缓冲区可选择性写入,请将其隐藏在上下文变量中或作为源文件中的静态变量,并且仅允许通过私有(private) API 调用(即:“getter”/“setter”函数)访问它)。
关于c - 将 const char * 传递给 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40032211/