我想知道是否有办法让 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 intx = 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/