我想知道是否有一种方法可以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);
}
Run Code Online (Sandbox Code Playgroud)
试图使之array = char*似乎不起作用。是否可以使char *指向char数组?
是否可以使char *指向char数组?
是。代替:
int main(){
char *c="Hello";
toup(c);
}
Run Code Online (Sandbox Code Playgroud)
使用:
int main(){
char c[] = "Hello";
toup(c);
}
Run Code Online (Sandbox Code Playgroud)
char *c = "Hello";使字符串为const,通常将字符串放入const数据节中。char c[] = "Hello";提供所需的可变字符串。
另请参见为什么从字符串常量到'char *'的转换在C中有效,但在C ++中无效。
另请参阅Blaze的评论:
for (int x;x<strlen(c);x++)x未初始化。你是说intx = 0吗?
其他两个警告...
void toup(char* c) {
char array[sizeof(c)];
for (int x;x<strlen(c);x++){
array[x]=toupper(c[x]);
}
}
Run Code Online (Sandbox Code Playgroud)
首先,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]);
}
}
Run Code Online (Sandbox Code Playgroud)
类似的问题是如何在C中迭代字符串?另请参阅什么是数组衰减?