c++ - 如何让一个 char* 指向一个 char[]?

标签 c++ c

我想知道是否有办法让 char* 指向 char 数组的内容,这样我就可以修改 char*跨功能。

例如

void toup(char* c) {
  char array[sizeof(c)];
  for (int x;x<strlen(c);x++){
    array[x]=toupper(c[x]);
  }
}

int main(){
  char *c="Hello";
  toup(c);
}

尝试使 array = char* 似乎不起作用。是否可以让char*指向char数组?

最佳答案

Is it possible to make the char* point to the char array?

是的。而不是:

int main(){
  char *c="Hello";
  toup(c);
}

使用:

int main(){
  char c[] = "Hello";
  toup(c);
}

char *c = "Hello";使字符串 const 并且通常将字符串放在 const 数据部分中。 char c[] = "Hello";提供您想要的可变字符串。

另见 Why is conversion from string constant to 'char*' valid in C but invalid in C++ .


另见 Blaze's comment :

for (int x;x<strlen(c);x++) x is uninitialized. Did you mean int x = 0?


另外两个注意事项...

void toup(char* c) {
  char array[sizeof(c)];
  for (int x;x<strlen(c);x++){
    array[x]=toupper(c[x]);
  }
}

首先,toup正在修改本地数组。在函数外是不可见的。

第二,sizeof(c)产生 4 或 8,因为它占用了指针的大小。这意味着声明是 char array[4];在 32 位机器上,或 char array[8];在 64 位机器上。

array[x]=toupper(c[x]);当字符串的长度为 c 时应该出现段错误比指针大。

你可能应该这样做:

void toup(char* c) {
  for (size_t x=0;x<strlen(c);x++){
    c[x]=toupper(c[x]);
  }
}

类似的问题在 How to iterate over a string in C?另见 What is array decaying?

关于c++ - 如何让一个 char* 指向一个 char[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57620668/

相关文章:

c - C/C++ 中的指针/数组语法 (char **p, *p[n])

c++ - std::strlen 如何在内部工作?

c++ - 清理代码的正确方法是什么?

c++ - 如何增加 std::shared 指针的所有权计数

c - int最快的c算术方法

c - "int *(*pfp) ();"在 C 中做什么?

c - 在 C 中,给定一个可变参数列表,如何使用它们构建函数调用?

c++ - 有符号字节和奇偶校验字节的区别

c++ - C++ CLI 应用程序 32 - 64 位 CString 问题

c - 为什么我使用以下代码从 valgrind 获取 "invalid read"和 "invalid write"?