我正在爲面試練習。目前我遇到的問題是在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