c - 将 const char * 传递给 C 函数

标签 c pointers char

对于以下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(您应该尽量避免,因为这样做的合法理由很少)对您没有帮助。

,如果您想使缓冲区可选择性写入,请将其隐藏在上下文变量中或作为源文件中的静态变量,并且仅允许通过私有(private) API 调用(即:“getter”/“setter”函数)访问它)。

关于c - 将 const char * 传递给 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40032211/

相关文章:

c - 内存重复错误

c - C函数中的全局变量和返回多个可变长度数组(指针)

C:这个char指针赋值有什么问题?

c++ - 检查字符数组 - 每次都返回相同的答案

java - 如果需要的话,在Java中添加两个二进制字符串(包括填充)的有效方法是什么?

c - 为什么每次调用不同的函数时都会出现<null>?

c - 取消引用指针时的竞争条件

与控制台输出混淆,C/USB CDC/PIC18F2550

c++ - 取消对结构的 int 指针地址的引用

c++ - C++ 中的字符指针