我正在为面试练习。目前我遇到的问题是在C中反转一个常量字符串。我知道既然str2是const,我可以修改str2的位置,但不能修改它的值。我有一个名为reverse_const的函数。它将反转const char * str_const并将其打印出来。但是,当我尝试从main方法反转后打印st2时,字符串不再被反转。它就像reverse_const()暂时改变str2的内存位置。我在这里做错了什么?修改C中的const char *
#include <stdio.h>
#include <string.h>
void reverse(char *str){
int c_size = strlen(str);
char *c_begin = str, *c_end = str + (c_size - 1);
int i;
for(i = 0; i < c_size/2; i++){
*c_begin ^= *c_end;
*c_end ^= *c_begin;
*c_begin ^= *c_end;
c_begin++;
c_end--;
}
}
void reverse_const(const char *str_const){
int c_size = strlen(str_const);
char str[c_size];
strcpy(str, str_const);
char *c_begin = str, *c_end = str + (c_size - 1);
int i;
for(i = 0; i < c_size/2; i++){
*c_begin ^= *c_end;
*c_end ^= *c_begin;
*c_begin ^= *c_end;
c_begin++;
c_end--;
}
str_const = str;
printf("%s\n", str_const);
}
int main(){
char str1[] = "Indiana";
char *str2 = "Kentucky";
printf("TESTS:\nString 1 pre-reversal: %s\n", str1);
reverse(str1);
printf("String 1 post-reversal: %s\n", str1);
printf("Constant string 2 pre-reversal: %s\n", str2);
reverse_const(str2);
printf("Constant string 2 post-reversal: %s\n", str2);
}
'char str [c_size];'不足以保存长度为'c_size'的* nul-terminated *字符串。 – Kninnug
_我在这里做错了什么?_你没有做任何改变'str2'指向的地方。你已经知道你需要改变它的位置来解决这个问题......但是环境也很重要! 'str_const = str;'对'main()'上下文中的'str2'没有影响。 – mah
“我可以将位置str2点修改为”不是如果该位置是恒定的。指针不是数组或字符串(并且数组不是字符串)。请阅读一本好C书中的指针,数组和字符串文字。 – Olaf